ekeith
ekeith

Reputation: 644

How to check if an array has enough positions to accept new values to the array in Java?

I'm creating a commercial airline flight program and I'm an amateur at Java (learning new things everyday). So, I have an array of strings called seats, each position in this array corresponds to an available seat on the flight. Initially these seats are all empty.

String[] seats = new String[8];

In the long-run, this program is going to be inserting values into this array and my question is how can I check if there are enough seats or positions in this array to accept new passengers to assign them seats? plus if there are no seats available, I want my program to display an error message and not assign seats to anyone in the group. Here is what I came up with so far,

for(int i=0; i< seats.length-1;i++) {
   if(seats[i] != null) {
     do something;
   } else {
       system.out.println("No seats available");
       (how do I not assign seats or accept more values to my array?)
   }
}

Do you think I am on the right track with this code? if not, corrections/contributions would be helpful. How do I instruct the program not to assign seats if there are no empty or available spots on the flight?

Upvotes: 4

Views: 1179

Answers (4)

zdenda.online
zdenda.online

Reputation: 2514

Your code is almost right. But for "no seats" may not be correct. That will work only when you occupy seats from the beginning. Your app may extend, so I would rather use something like described below where addPassenger method returns true if insertion succeeds, otherwise false.:

private static int MAX_SEATS = 8;
private String[] seats = new String[MAX_SEATS];

public boolean addPassenger(String passengerName) {
    for (int i = 0; i < seats.length; i++) {
        if (seats[i] == null) {
            seats[i] = passengerName;
            return true;
        }
    }
    return false;
}

Anyway in the end I would recommend you to use more objective approach to allow further extensibility. I mean using Passenger, Seat, Plane classes. Something like:

public class Plane {

    private Seat[] seats;

    public Plane(int capacity) {
        this.seats = new Seat[capacity];
        for (int i = 0; i < seats.length; i++) {
            seats[i] = new Seat();
        }
    }

    public boolean addPassenger(Passenger passenger) {
        for (Seat seat : seats) {
            if (!seat.isOccupied()) {
                seat.setPassenger(passenger);
                return true;
            }
        }
        return false;
    }

    public boolean addPassengers(Passenger... passengers) {
        if (passengers == null) {
            throw new IllegalArgumentException("Passengers cannot be null");
        }
        if (!hasFreeSeats(passengers.length)) {
            return false;
        } else {
            for (Passenger passenger : passengers) {
                addPassenger(passenger);
            }
            return true;
        }
    }

    private boolean hasFreeSeats(int count) {
        int seatsNeeded = count;
        for (Seat seat : seats) {
            if (!seat.isOccupied()) {
                seatsNeeded--;
            }
            if (seatsNeeded == 0) {
                return true;
            }
        }
        return false;
    }

}

public class Seat {

    private Passenger passenger;

    public boolean isOccupied() {
        return passenger != null;
    }

    public void setPassenger(Passenger passenger) {
        this.passenger = passenger;
    }

    // getter for passenger and other fields   
}

public class Passenger {

    private final String name;

    public Passenger(String name) {
        this.name = name;
    }

    // getter for name and other fields
}

Please note I used Java 7 language level as it may be easier for you to understand. The code can be slighly smaller if I would use Java 8 stream API for collections.

Upvotes: 1

Nate
Nate

Reputation: 549

There are plenty of good answers here about how to handle your issues with arrays, but it sounds to me like you could more easily solve your problem by hiding your array inside a Flight class that could separately track the number of open seats within itself. Below is a runnable example that tracks how many open seats are available and allows expanding the array if you run out of open seats.

import java.util.Arrays;
import java.util.Scanner;

public class Flight {
    private String[] seats;
    private int      openSeatCount;

    public Flight(int seatCount) {
        this.seats         = new String[seatCount];
        this.openSeatCount = seatCount;

        System.out.println("Created a new flight with " + seatCount + " seats");
    }

    public boolean addNewPassengers(String...newPassengers) {
        System.out.println("Adding " + newPassengers.length + " passengers: " + Arrays.toString(newPassengers));

        if (newPassengers.length > openSeatCount) {
            System.out.println("The new passengers could not be added, " + 
                newPassengers.length + " seats were requested but only " + openSeatCount + " are open");
            return false;
        }
        else {
            for (String newPassenger : newPassengers) {
                seats[getFirstOpenSeatIndex()] = newPassenger.trim();
                openSeatCount--;
            }

            System.out.println("All " + newPassengers.length + " new passengers were added. " + openSeatCount + " open seats are remaining");
            return true;
        }
    }

    public void addSeats(int seatCountToAdd) {
        this.seats = Arrays.copyOf(seats, seats.length + seatCountToAdd);
        openSeatCount += seatCountToAdd;
        System.out.println("Added " + seatCountToAdd + " seats. The new seat count for the flight is " + seats.length);
    }

    public int getOpenSeatCount() {
        return openSeatCount;
    }

    public String[] getAllPassengers() {
        return Arrays.copyOf(seats, getFirstOpenSeatIndex());
    }

    private int getFirstOpenSeatIndex() {
        return seats.length - openSeatCount;
    }

    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            boolean stillAddingPassengers = true;

            System.out.print("Please input the number of seats available on the flight: ");
            int seatCount = input.nextInt();
            Flight flight = new Flight(seatCount);

            while (stillAddingPassengers) {
                System.out.print("Please input names of passengers you would like to add separated by commas: ");
                String[] newPassengers = input.next().split(",");

                if (!flight.addNewPassengers(newPassengers)) {
                    System.out.print("Would you like to add open seats to accomodate all of your new passengers? (Y/N): ");
                    boolean accomodateNewPassengers = getBooleanInput(input);

                    if (accomodateNewPassengers) {
                        int openSeatShortfall = newPassengers.length - flight.getOpenSeatCount(); 
                        flight.addSeats(openSeatShortfall);
                        flight.addNewPassengers(newPassengers);
                    }
                }

                System.out.print("Would you like to add more passengers? (Y/N): ");
                stillAddingPassengers = getBooleanInput(input);
            }

            System.out.println("Your flight contains the following passengers: " + Arrays.toString(flight.getAllPassengers()));
        }
    }

    private static boolean getBooleanInput(Scanner input) {
        return "y".equalsIgnoreCase(input.next());
    }
}

Example console output from the running program:

Please input the number of seats available on the flight: 2
Created a new flight with 2 seats
Please input names of passengers you would like to add separated by commas: Nate,Lauren
Adding 2 passengers: [Nate, Lauren]
All 2 new passengers were added. 0 open seats are remaining
Would you like to add more passengers? (Y/N): y
Please input names of passengers you would like to add separated by commas: Sawyer
Adding 1 passengers: [Sawyer]
The new passengers could not be added, 1 seats were requested but only 0 are open
Would you like to add open seats to accomodate all of your new passengers? (Y/N): n
Would you like to add more passengers? (Y/N): y
Please input names of passengers you would like to add separated by commas: Jackson,Sawyer,Collins
Adding 3 passengers: [Jackson, Sawyer, Collins]
The new passengers could not be added, 3 seats were requested but only 0 are open
Would you like to add open seats to accomodate all of your new passengers? (Y/N): y
Added 3 seats. The new seat count for the flight is 5
Adding 3 passengers: [Jackson, Sawyer, Collins]
All 3 new passengers were added. 0 open seats are remaining
Would you like to add more passengers? (Y/N): n
Your flight contains the following passengers: [Nate, Lauren, Jackson, Sawyer, Collins]

Upvotes: 1

Michael
Michael

Reputation: 2773

There are a few possible ways to acheice your program. One is to use an array like you have now, and keep filling it up until there are no more null values left. Another possibility is to use an ArrayList; essentially, it's an array that can grow and shrink in size.

METHOD 1

nullValueCount is not defined here, you'll have to code that (though it won't be too hard.)

String seats = new String[8];
if (nullValueCount(seats) == 0){
    //all filled up, sorry!
}else{
    //good to go, add in more!
}

METHOD 2

ArrayList<Sting> seats = new ArrayList<String>();
final int MAX_SEATS = 8;
if (seats.size() >= MAX_SEATS){
    //sorry, it's filled up
}else{
    //good to go!
}

Upvotes: 0

John Bupit
John Bupit

Reputation: 10618

Several ways to do this. You are on the right track. One way would be to check whether k (where k is the number of passengers in the group) seats are available before actually inserting them. Here's how:

int emptyCount = 0;
for(int i = 0; i < seats.length - 1; i++) {
   if(null == seats[i]) emptyCount++;
}

if(emptyCount >= k) {
    // Safely proceed with the insertions.
} else {
    // Display an error. Do not book tickets.
}

Upvotes: 1

Related Questions