Home > database >  Find first empty seat in an 2d array list
Find first empty seat in an 2d array list

Time:10-01

public static void main(String[] args) {

    boolean[][] aud = { { true, true, true, true }, // rad 0
            { false, false, true, false }, // rad 1
            { true, false, true, true }, // rad 2
            { true, true, true, true }, // rad 3
    };


public static void firstEmptySeat(boolean[][] array) {
    
    
    String a = "";
    
    for (int i = 0; i < array.length; i  ) {

        for (int j = 0; j < array[i].length; j  ) {
            
            if (array[i][j] == false) {
                
                a = i   ","   j;
            }
        }
        
    }
    System.out.println(a);
}

Me and my friend are trying to find the first empty seat in a 2d array called aud. False matches to an empty seat. We are supposed to print out the first empty seat in the array, and its index, but our code only gives us the last empty seat. Can anyone help?

CodePudding user response:

Add a break statement when the condition is fulfilled. And for the outer loop, you can use a flag.

public static void firstEmptySeat(boolean[][] array) {
    
    
    String a = "";
    bool flag = true;
    for (int i = 0; i < array.length; i  ) {

        for (int j = 0; j < array[i].length; j  ) {
            
            if (array[i][j] == false) {
                
                a = i   ","   j;
                flag = false;
                break;
            }
        }
        if(flag == false)
           break;
    }
    System.out.println(a);
}
  • Related