如何检查数组是否有足够的位置来接受Java中的数组的新值?

时间:2015-09-28 22:13:23

标签: java arrays string if-statement

我正在创建一个商业航空公司的飞行计划,我是Java的业余爱好者(每天都在学习新东西)。所以,我有一个叫做座位的字符串数组,这个数组中的每个位置都对应于航班上的可用座位。最初这些座位都是空的。

String[] seats = new String[8];

从长远来看,这个程序将在这个阵列中插入值,我的问题是如何检查这个阵列中是否有足够的座位或位置接受新乘客分配座位?加上如果没有座位可用,我希望我的程序显示错误消息,而不是为组中的任何人分配座位。 这是我到目前为止所提出的,

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

你认为我使用这段代码走在正确的轨道上吗?如果没有,更正/贡献会有所帮助。如果航班上没有空位或可用位置,我如何指示程序不分配座位?

4 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。你走在正确的轨道上。一种方法是检查k(其中k是该组中的乘客数量)座位是否可用 实际插入之前。以下是:

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

答案 1 :(得分:1)

您的代码几乎是正确的。但是对于&#34;没有座位&#34;可能不正确。只有当你从一开始就占据座位时,这才有效。你的应用可能会扩展,所以我宁愿使用下面描述的内容,如果插入成功,addPassenger方法返回true,否则为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;
}

无论如何,最后我建议你使用更客观的方法来进一步扩展。我的意思是使用Passenger,Seat,Plane类。类似的东西:

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
}

请注意我使用Java 7语言级别,因为您可能更容易理解。如果我将Java 8流API用于集合,那么代码可以小得多。

答案 2 :(得分:1)

这里有很多关于如何处理数组问题的好答案,但听起来我觉得你可以通过将数组隐藏在Flight类中来更轻松地解决问题,可以单独跟踪其中的开放座位数本身。下面是一个可运行的示例,它跟踪可用的开放座位数,并允许在开放座位用完时扩展阵列。

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

正在运行的程序的控制台输出示例:

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]

答案 3 :(得分:0)

有几种方法可以让您的程序变得更好。一种是像现在一样使用数组,并继续填充它,直到不再有static IEnumerable<byte[]> Where(this IEnumerable<byte[]> source, Func<byte[], bool> predicate) { } 个值。另一种可能性是使用null;基本上,它是一个可以增大和缩小的数组。

<方法1 这里没有定义

ArrayList,你必须编写代码(虽然它不会太难。)

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