AppSensei
AppSensei

Reputation: 8400

Check if array elements are filled in java

I'm working on a simple reservation system with 10 elements (seats). I want to check if elements from 1 to 5 has been set. If Yes, then set the elements from 6 to 10 (Vice-Versa).

An element should not be assigned a value more than once. My code so far.

    boolean[] seats = new boolean[10];

    Scanner input = new Scanner(System.in);
    System.out.print("Choose FirstClass(1) / Economy(2): ");
    int flightClass = input.nextInt();

    for (int j = 0; j < seats.length; j++) {
        System.out.println("\nEnter Seat Number: ");
        int enterSeat = input.nextInt();
        if (flightClass == 1) {
            if (enterSeat >= 0 && enterSeat <= 5) {
                System.out.println("You're in the First Class.");

                seats[enterSeat] = true;
                System.out.printf("You're Seat Number is %d\n", enterSeat);

            }

        } else if (flightClass == 2) {
            if (enterSeat >= 6 && enterSeat <= 10) {
                System.out.println("You're in the Economy.");

                seats[enterSeat] = true;
                System.out.printf("You're Seat Number is %d\n", enterSeat);
            }

        }

My Question: How do I check if elements from 1 to 5 has been set, and if they have, set the elements from 6 to 10, and vice versa?

For example:

Enter seat no. to book: 1

Enter seat no. to book: 2

Enter seat no. to book: 3

Enter seat no. to book: 4

Enter seat no. to book: 5

All the first class seats(1-5) has been set. Now the remaining seats are from 6 - 10.

Enter seat no. to book: 6 so on...

Upvotes: 5

Views: 1876

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Arrays in Java1 are indexed from zero, not from one. Therefore, your code that checks >=1 and <=10 should be changed to >=0 and <=9, or use2

seats[enterSeat-1]

instead of

seats[enterSeat]

To find the next available element from among the elements of a sub-array, you can use this loop:

int firstFree = -1;
for (int j = 0 ; j != 5 ; i++) {
    if (!seat[j]) {
        firstFreeSeat = j;
        break;
    }
}
if (firstFreeSeat == -1) {
    System.out.printl("Sorry!");
}


1 As well as C, C++, C#, Objective C, and many other languages

2 This is something you may want to do if you expect the user to enter numbers one through ten rather than zero through nine - a more natural choice for seat numbering.

Upvotes: 6

Related Questions