简体   繁体   中英

Return the index of a 2D Array

I'm writing a method that searches for a value in a 2D array. Upon finding the value I want to return the value's index. Is there a way to return the index of the value without returning another array?

If you really want to not return an array nor string with both integers, you could create a class with two attributes (x,y), and return an instance of that class. But I don't see why you would do this

Class be looking like:

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;}
}

Or use Point class from package java.awt

You have no other solution but to return the two indices:

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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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