I have an int[3][3] array and it contains only 0 or 1 values, if the value is 1 I want to add the coordinates of this value in the ArrayList as int[2] array, but I don't know why it always add the last 1-value coordinates, what's the problem?
public static void main(String[] args) {
Random random = new Random();
int[] coordinates = new int[2];
ArrayList<int[]> arrayList = new ArrayList<>();
int[][] board = new int[3][3];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = random.nextInt(2);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
if (board[i][j] == 1){
coordinates[0] = i;
coordinates[1] = j;
arrayList.add(coordinates);
}
}
System.out.println();
}
System.out.println("coordinates of cells that contain 1 value");
for (int[] coordianate : arrayList) {
for (int i = 0; i < coordianate.length; i++) {
System.out.print(coordianate[i] + " ");
}
System.out.println();
}
}
}
output:
1 0 1
1 1 0
1 1 0
coordinates of cells that contain 1 value
2 1
2 1
2 1
2 1
2 1
2 1