繁体   English   中英

返回二维数组的索引

[英]Return the index of a 2D Array

我正在编写一种在2D数组中搜索值的方法。 找到值后,我想返回值的索引。 有没有一种方法可以返回值的索引而不返回另一个数组?

如果您确实不想同时返回两个整数都不是的数组或字符串,则可以创建一个具有两个属性(x,y)的类,然后返回该类的实例。 但是我不明白你为什么要这么做

类看起来像:

public class MyIndex{
    int x;
    int y;

    public MyIndex(int x, int y){
       this.x=x;
       this.y=y;
    }

    public int getX() {return x;}
    public void setX(int x) {this.x = x;}
    public int getY() {return y;}
    public void setY(int y) {this.y = y;}
}

或者使用包java.awt中的Point类

除了返回两个索引,您没有其他解决方案:

public static int[] find(int a[][], int val) {
    for(int i = 0 ; i < a.length ; ++i) {
        for(int j = 0 ; j < a[i].length ; ++j) {
            if(a[i][j] == val) {
                return new int[] {i, j};
            }
        }
    }
    return null;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM