java - 返回数组的问题

标签 java arrays

我有一个 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/

相关文章:

windows - Java日历问题,JDK 1.6.0.22

java - 无法通过类中的 Runnable 访问全局变量

Java EE session : Can you store some attributes as non-persistent?

C# 获取带路径的数组的文件大小

javascript - 在 JS 中检查一个数组与另一个数组的值

java - 如何从文件中读取用户定义的对象?

java - 无法从我的 public void writeOutput 中获取 add.getSum() 等

java - jit 会优化分支太少的 switch 语句吗?

c# - 按属性同时对 2 个数组进行排序

javascript - 规范化对象数组中的数据 (JavaScript)