Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find first empty seat in an 2d array list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading