0

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] = '*';
 } 
}
nem035
35.5k6 gold badges93 silver badges104 bronze badges
asked Sep 23, 2014 at 2:08
3
  • Is this the code you need help with? Commented Sep 23, 2014 at 2:12
  • 2
    @Kerppag that will not work. array.length gives the length of the allocated space, not the number of items actually present Commented Sep 23, 2014 at 2:12
  • ok ok @nem i just tried it and it fails. i guess 2d array should be checked manually? Commented Sep 23, 2014 at 2:15

2 Answers 2

3

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;
}
answered Sep 23, 2014 at 2:16
1

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
}
answered Sep 23, 2014 at 2:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.