Still Training
Still Training

Reputation: 9

Check If Two Dimensional Array is empty

I'm working on a class project and hit a roadblock. I've been looking everywhere on how to check if a Two Dimensional Array is empty and if so then it'll continue on with the project. If the array is full then it'll ask the customer to be put on a waiting list. I'm really new to java so if you can please help me out with this! I've been thinking of using a boolean statement but I'm not sure if that'll work. Any case I've written this so far for the array.

char [][] seats = new char [13][6]; //array for row and columns 

for (int row = 0; row < seats.length; row ++) {//output seating to * with no passengers
    for (int col = 0; col < seats[row].length; col ++) {
        seats [row][col] = '*';
    }   
}

Upvotes: 0

Views: 8512

Answers (2)

nem035
nem035

Reputation: 35491

It depends on your definition of empty...

You could do a check if each item in the array equals a special value that means "empty" item.

The fastest way to do that is to check item by item, and return false as in "not-empty" as soon as you find a taken seat. If we checked all seats and no taken seats were found then the matrix is empty.

boolean areAllSeatsEmpty(char [][] seats) {
    final char EMPTY_SEAT = '*';
    for (int row = 0; row < seats.length; row ++) {
        for (int col = 0; col < seats[row].length; col ++) {
            if(seats [row][col] != EMPTY_SEAT) { // return false as soon as a non-empty seat is found
                return false;
            }
        }
    }
    return true;  // no non-empty seats were found so all seats are empty
}

Upvotes: 1

Mshnik
Mshnik

Reputation: 7032

Judging by your question, you want to take in an array of chars and either:

  1. Output true if there is at least one open seat (*)
  2. Output false if there isn't.

You want code that looks like this:

public static boolean hasOpenSeat(char[][] seats){
    for(int i = 0; i < seats.length; i++){
        for(int j = 0; j < seats[i].length; j++){
            if(seats[i][j] == '*') 
                return true;
        }
    }
    //Open seat was never found - return false
    return false;
}

Upvotes: 3

Related Questions