lundi 28 septembre 2015

How to check if an array has enough empty/null "consecutive" positions to place values together randomly in Java?

I'm creating a commercial airline flight program and I'm still learning how to get around with Java. So, I was wondering if there was any way to check if an array has enough consecutive positions to place values together in those positions in the array? For example, 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 I want my program to be able to check if there are any empty seats(positions) in the flight(array) to assign a passenger to a seat. I sketched this to check.

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?)
   }
}

but advised on using an objective approach, I got to this

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;
}

If the program finds an empty seat after checking, It should then check again if there are empty consecutive seats. (For example, if we wanted to make 3 passengers seat together, the program should check if there are empty 3 seats and then seat them there). If the program finds 3 consecutive positions in the array, it should randomly assign the passengers to whichever 3 position. otherwise it should randomly try another seat, repeating until successful. Right now, my array of seat can take up to 8 values, so the possible 3 positions could be (1,2,3 or 2,3,4 or 3,4,5 or 4,5,6 or 5,6,7). If the program does not find a consecutive position to seat these 3 people, it should randomly place them in different positions.(pick random seat numbers till it can find an empty seat) This code is just adding passengers to the seats array .

//accepting more values to the seats array
public boolean addPassengers(String... passengerNames) {
    boolean everyoneAdded = true;
    for (String passengerName : passengerNames) {
        everyoneAdded = everyoneAdded && addPassenger(passengerName);
    }
    return everyoneAdded;
}

How is it possible to check for consecutive positions in an array in order to add groups of passengers randomly? Any correction/contribution would be helpful.

1 commentaire: