Skip to content
Advertisement

How to use findAny() to find a spesific value in a 2D Array

I have a 2D array as follows

int[][] seatsPrices = {{10,10,10,10,10,10,10,10,10,10},
                        {10,10,10,10,10,10,10,10,10,10},
                        {10,10,10,10,10,10,10,10,10,10},
                        {10,10,20,20,20,20,20,20,10,10},
                        {10,10,20,20,20,20,20,20,10,10},
                        {10,10,20,20,20,20,20,20,10,10},
                        {20,20,30,30,40,40,30,30,20,20},
                        {20,30,30,40,50,50,40,30,30,20},
                        {30,40,50,50,50,50,50,50,40,30}};

I’m asking the user to give a number. Let’s say he gives 20. So, I want to code to compare that value with the seatsPrices array iteratively and find any i,j indexes of the seatsPrices array which its values is 20, and print it. I should probably use findAny() but I cannot figure out how to use it. Note: I need to find only one “20” and stop. Thus, using two nested loop, it causes some problems for me.

Advertisement

Answer

I don’t know why you would use findAny(), it seems much simpler to just iterate over the arrays and search for 20 and print out the i,j whenever you come across one.

for (int i = 0; i < seatPrices.length; i++) {
    for (int j = 0; j < seatPrices[0].length; j++) {
        if (seatPrices[i][j] == 20) 
            System.out.println(i + " " + j);
    }
}

If you know anything about the arrays (like they’re sorted) you can come up with a quicker algorithm to find the indices.

If you want to find only one:

boolean found = false;
for (int i = 0; i < seatPrices.length && !found; i++) {
    for (int j = 0; j < seatPrices[0].length && !found; j++) {
        if (seatPrices[i][j] == 20) {
            System.out.println(i + " " + j);
            found = true;
        }
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement