简体   繁体   中英

Check for next 'false' element in array

I am trying to finish an exercise from a book in a chapter covering arrays.

The exercise prompts the user to enter 1 to be assigned a seat in first class (seats 1 - 5) and to enter 2 to be assigned a seat in economy (seats 6 - 10). I got that part (I think so!)

If the user enters a number (let's say 2) and all economy seats are full ( seats[5] through seats[9] are true ) I need to ask the user if he'd like to be moved to first class. I am stuck here, trying to figure out how to check, in the example I mentioned, how to check for the next seat that isn't taken in first class (next 'false').

I would also love to hear some recommendations regarding how to make the code more 'elegant' and efficient, maybe use some subarrays ( firstClassSeats[] and economyClassSeats[] )

I'm still learning :)

This is the code:

    import java.lang.reflect.Array;
    import java.util.Arrays;
    import java.util.Scanner;

    public class AirlineReservationSystem {

/* Number of seats on the plane */
private static final int NUMBER_OF_SEATS = 10;

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int firstClass = 0;
    int economyClass = 5;
    int[] firstClassSeats = {1,2,3,4,5};
    int[] economyClassSeats = {6,7,8,9,10};


    /* Initialize array of seats and fill with false to indicate empty */
    boolean[] seats = new boolean[NUMBER_OF_SEATS];
    Arrays.fill(seats, false);

    while (isPlaneFull(seats) == false){
        System.out.printf("%nPlease type 1 for First Class%n" +
                "Please type 2 for Economy%n");
        int choice = input.nextInt();

        if (choice == 1){
            if(seats[firstClass] == false){
                seats[firstClass] = true;
                firstClass++;
            }

            for(boolean seatNumber : seats)
                System.out.printf("[%b]\t", seatNumber);

            if ( isPlaneFull(seats) == true){
                System.out.printf("%nThe plane is full. Next flight leaves in 3 hours");
            }

        }
        else{
            try{
                if(seats[economyClass] == false)
                {
                    seats[economyClass] = true;
                    economyClass++;

                    for(boolean number : seats)
                        System.out.printf("[%b]\t", number);

                }
            }
            catch (ArrayIndexOutOfBoundsException e){
                if (isPlaneFull(seats) == true){
                    System.out.printf("%nThe plane is full. Next flight leaves in 3 hours");
                }
                else
                {
                    System.out.printf("%nAll economy seats are full%n");
                }
            }



        }




    }


}

public static boolean isPlaneFull(boolean[] array){
    for(boolean b: array) if(!b) return false;
    return true;
}

}

How to do

To check whether first class is full, you need either to check whether the pointer to the last allocated first class seat is at the maximum, or whether all seats are taken, one by one :

boolean firstClassFull = true;
for(int i=0; i<5; i++){
   if(seats[i] == false){
      firstClassFull = false;
      seats[i] = true;
      break;
   }
}

Same for economy class.

This boils down to defining what "first class is full" means : it means that all seats in first class are taken. In order to check that, you need to check all seats.

What is wrong in your code

The idea of your code is to increment your firstClass variable, so that it represents the next available first class seat :

if(seats[firstClass] == false)

However, you can do that only if you restrain that variable to acceptable values (maximum 4 in your case). So you need to add a check

if(seats[firstClass] == false && firstClass < 5 ) 

In any case, it would probably be more robust to check all first class seats, instead of just checking what is supposed to be the "next available", since it would allow for someone to cancel their ticket, and release a seat.

Other notes about your code

Variables and their names

  • These variables

     int firstClass = 0; int economyClass = 5; 

    are wrongly named, they indicate the next available seat of the class, they should be named accordingly, for example:

     int nextAvailableFirstClassSeat = 0; int nextAvailableEconomyClassSeat = 5; 
  • Also, the start index of each class would be better handled as static final variables, like your other constant.

  • This is more or less the purpose of your other variables:

     int[] firstClassSeats = {1,2,3,4,5}; int[] economyClassSeats = {6,7,8,9,10}; 

    However, you don't need to define them that way, you can simply define a start and an end .

  • Wrapping up the two points above, you can replace this with

     private static final int FIRST_CLASS_START = 0; private static final int SECOND_CLASS_START = 5; 
  • Note that you actually don't need to specify an end, because first class ends where second class begins, and second class ends at end of plane.

  • Note also that since array indices are numbered from 0 to length-1 , the indices for first class and second class are 0-4 and 5-9 .

ArrayIndexOutOfBoundsException

  • IMPORTANT: Your try-catch block to catch an ArrayIndexOutOfBoundsException is wrong. This kind of exception is an unchecked exception , and is meant to signal a programming mistake. It makes no sense to try to catch it, as you already know when it can be thrown : that is when you try to access the array outside of its bounds. So you can, and should, simply test whether economyClass is smaller than seats.length

Inefficiencies

  • There is a small inefficiency in your code, because of your call to isPlaneFull after each request from user. This is inefficient, because you are re-scanning your array every time. You don't need to do that, because you could store the count of taken seats in a variable, increment that count each time you allocate a new seat, and simply check if that variable is equal to the maximum, instead of rescanning everything.

  • Also, you have some duplicated code : the part that prints out the array, and the part that tests if the plane is full, and if so announces departure time. You could move these parts of the code outside of the if-else so that it gets executed all the time.

  • You don't need Arrays.fill(seats, false); because by default arrays are initialized with the default value for the specified type. For boolean the default value is false .

  • Thus you also don't need import java.util.Arrays;
  • You don't need import java.lang.reflect.Array;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM