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

Posted

技术标签:

【中文标题】如何检查数组是不是有足够的位置来接受 Java 中数组的新值?【英文标题】:How to check if an array has enough positions to accept new values to the array in Java?如何检查数组是否有足够的位置来接受 Java 中数组的新值? 【发布时间】:2015-12-26 06:22:33 【问题描述】:

我正在创建一个商业航空公司的飞行计划,并且我是 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?)
   

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

【问题讨论】:

数组有一个固定大小。其中一些条目可能用null 填充,但这并不意味着那些null 条目不存在。 或多或少。您的 else 块是错误的,因为每次座位不空时都会触发。我会在循环之前添加一个计数器,在你的 if 块中增加它,然后在循环完成后将它与你想要就座的人数进行比较 【参考方案1】:

有几种可能的方法来实现您的程序。一种是像现在一样使用一个数组,并继续填充它,直到没有更多的null 值。另一种可能性是使用ArrayList;本质上,它是一个大小可以增长和缩小的数组。

方法 1

nullValueCount 未在此处定义,您必须对其进行编码(虽然不会太难。)

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

方法 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!

【讨论】:

ArrayList 不适合所描述的情况,因为飞机上的座位数量通常是固定的。 @njzk2 您可以轻松添加一些逻辑来施加限制 我不明白您错误地使用 String[8] 是什么意思。 :/ 因为席位是一个数组,如果我希望它在插入数组之前包含所有空值,它不应该是 String[ ] seat = new String[8] 吗? @迈克尔 是的,对不起,这是我的错,你做得对@girlCoder。我最初以为您使用的是自定义 Seat 类(顺便说一句,您应该这样做)【参考方案2】:

有几种方法可以做到这一点。你在正确的轨道上。一种方法是检查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.

【讨论】:

【参考方案3】:

您的代码几乎是正确的。但对于“没有座位”可能并不正确。这只有在您从一开始就占据座位时才会起作用。您的应用程序可能会扩展,因此我宁愿使用如下所述的内容,其中 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;

无论如何,最后我建议您使用更客观的方法来实现进一步的可扩展性。我的意思是使用乘客、座位、飞机类。比如:

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 用于集合,代码会稍微小一些。

【讨论】:

感谢您的建议! :)【参考方案4】:

这里有很多关于如何处理数组问题的好答案,但在我看来,您可以通过将数组隐藏在可以单独跟踪其中开放座位数的 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]

【讨论】:

以上是关于如何检查数组是不是有足够的位置来接受 Java 中数组的新值?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用指针检查数组中的某个位置是不是被修改

list遍历陷阱分析原理

如何检查Mysql中是不是存在数组元素?

如何检查字节数组是不是包含 Java 中的 Unicode 字符串?

如何检查对象是不是不是数组?

Java - 如何检查字符串是不是包含字符串数组的元素?