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;


if(rotarray[x-1][y] == true)

but both failed with "ArrayIndexOutOfBoundException: -1"

I am using Processing 2.2.1


  • _vk_vk
    edited May 2015 Answer ✓

    That's because there is no "values before" x when x = 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 when x = 0 check only value after x. Something like this.

  • Answer ✓
  • Thanks guys :) Haven't thought on this

  • About your code fragment:

    if(rotarray[x][y] == true)
        return true;
        return false;

    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:

    if (rotarray[x][y])

    Reads better if you choose the variable name better:

    if (rotatedItems[x][y])

    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:

    if (x > 10) return true; else return false;

    you can just write:

    return x > 10;

    Here, the returned value is just the value from your array, you can replace the four initial lines with:

    return rotarray[x][y];

    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 as if (foo = true) (the only case in Java where an assignment is legal in a condition...) and wonder why their program doesn't work... :-)

Sign In or Register to comment.