We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there, I have a question, I have an array, and a variable x. I want to know the values before and after x in the array. But I have no clue how to read in the value before x. I have tried two opportunities:
x--;
if(rotarray[x][y] == true)
return true;
else
return false;
and
if(rotarray[x-1][y] == true)
but both failed with "ArrayIndexOutOfBoundException: -1"
I am using Processing 2.2.1
Answers
That's because there is no "values before"
x
whenx = 0
. So you can't check that. You need to deal with this. Depending on what you need. Perhaps start checking at index 1. Or whenx = 0
check only value afterx
. Something like this.https://processing.org/reference/Array.html
x = max(x - 1, 0);
:https://processing.org/reference/max_.html
Thanks guys :) Haven't thought on this
About your code fragment:
You are not using booleans properly.
First, you should never (have to) use == true or == false.
You can just use the boolean as a condition, it is designed this way:
Reads better if you choose the variable name better:
or similar, depending on the meaning of the boolean. Note the plural, denoting multiple instances, avoiding the redundant 'array' part.
Actually, you can avoid the
if
altogether. If, after a condition, you return either true or false, you can just return the condition itself. For example, instead of:you can just write:
Here, the returned value is just the value from your array, you can replace the four initial lines with:
A bit off-topic, but applying these ideas can improve the readability of your code.
Thank you PhilHo, :-bd and if I would use this you are absolut right:
if(rotarray[x][y] == true) return true; else return false;
(my solution was not very smart :D)
but for readable reasons I decided for this:
if(rotarray[x-1][y] == true)
perhaps I rename the Array. But this won't give back a boolean :)
Side note: I often advise against
if (foo == true)
because people sometime mistype it asif (foo = true)
(the only case in Java where an assignment is legal in a condition...) and wonder why their program doesn't work... :-)