【发布时间】:2015-08-16 23:28:26
【问题描述】:
我有一个 int[3][3] 数组,它只包含 0 或 1 个值, 如果值为1我想在ArrayList中添加这个值的坐标为int[2]数组,但是不知道为什么总是添加最后一个1值的坐标,有什么问题?
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();
}
}
}
输出:
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
【问题讨论】: