我有一个 2D int[][] 并且正在尝试编写一个函数来在该数组中定位一个 0 并返回一个包含其坐标的数组。
我想到了这个:
public int[] locateZero(int[][] array) {
int[] coordinates = new int[2];
for (int i=0; i < array.length; i++) {
for (int j=0; j < array[0].length; j++) {
if (array[i][j] == 0) {
//The following line doesn't work!
coordinates.add(i, j);
}
}
}
return coordinates;
}
NetBeans 保留 add
方法的底层,声明它找不到它。
有人能帮帮我吗?
我知道这是个愚蠢的问题。我是 Java 菜鸟。
最佳答案
您的数组名为 coordinates
是一个数组。数组不支持 add()
功能。如果你想有一个添加功能,使用ArrayList<Integer>
相反。
不过,更典型的做法是像这样将值分配给数组:
public int[] locateZero(int[][] array) {
int[] coordinates = new int[2];
for (int i=0; i < array.length; i++) {
for (int j=0; j < array[0].length; j++) {
if (array[i][j] == 0) {
//here is the difference
coordinates[0] = i;
coordinates[1] = j;
}
}
}
return coordinates;
}
关于java - 返回数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49957183/