Reputation: 267
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]);
}
}
Upvotes: 0
Views: 1690
Reputation:
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.
Upvotes: 1