0

Iam trying to create a java program in which, i will be able to change the position of value 1 to specific positions into an array.For example i have the value 1 in the position [5][4] and i want to move it to the next (or the previews position) and delete the value 1 and store the value 0 into the previous position. My problem is that i can move the value 1 but i can't delete it from the previous position(store to the previous position the value 0).My code is the following:

for (int row = 0; row < 6; row++) {
    for (int col = 0; col < 6; col++) {
        int randomPosition = r.nextInt(2);

        array[row][col] = 0;
        array[2][3] = 1;
        array[4][4] = 1;

        if (array[row][col] == 1) {
            array[row][col] = 0;

            if (randomPos == 0) {
                array[row - 1][col] = 1;

            } else if (randomPos == 1) {
                array[row][col - 1] = 1;

            } else if (randomPos == 2) {
                array[row + 1][col + 1] = 1;

            }
        }
    }
}

for (int row = 0; row < cells.length; row++) {
    for (int col = 0; col < cells[row].length; col++) {
        System.out.print("  " + cells[row][col]);
    }
}
3
  • Please elaborate "I can't". Real output vs. expected output, err messages, etc.. Commented Jan 26, 2012 at 18:48
  • Please include the real code. Those loop bodies are incomplete and make no sense. Commented Jan 26, 2012 at 18:51
  • If this is homework, please tag it as such. Commented Jan 26, 2012 at 19:19

1 Answer 1

1

You're probably getting an ArrayIndexOutOfBoundsException. This is because you're referencing [row-1] and [col-1] (and +1 as well), but row or col might be 0 or the maximum index, and adding or subtracting 1 in those cases will make you try to reference an index that doesn't exist.

You'll have to put in checks to make sure that the index you're referencing actually exists.

Example:

if(randomPos==0){
    if(row-1 > 0)
        array[row-1][col] = 1;
}

Also, as per the comments, you should tell us what you're actually seeing, and how you know it's not working correctly. If there are any error messages that you can't make sense of (try reading them first, of course!), then post those as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.