我正在建立一个预订系统,在这里我要求用户提供登机和目的地。有六个车站,我想从登机和目的地以及所有中间车站减去乘客人数。

TrainService.java类:

// Prompt user for the boarding point.
System.out.println("\n0. Lorem");
System.out.println("1. Ipsum");
System.out.println("2. Dolor");
System.out.println("3. Sit");
System.out.println("4. Amet\n");

System.out.print("Select a boarding point: ");
String boardingPoint = sc.nextLine();
int boardingPointNum = Integer.parseInt(boardingPoint);

// Prompt user for the destination point.
System.out.println("\n1. Ipsum");
System.out.println("2. Dolor");
System.out.println("3. Sit");
System.out.println("4. Amet");
System.out.println("5. Consectetur\n");

System.out.print("Select a destination point: ");
String destinationPoint = sc.nextLine();
int destinationPointNum = Integer.parseInt(destinationPoint);

// Reduce the number of available seats to the respective stations.
for (int i = 0; i < 5; i++) {
    if (boardingPoint.equals("0") && destinationPoint.equals(Integer.toString(i + 1))) {
        numOfFirstClassSeats[0 - i] -= numOfFirstClassAdults;
        stationList.setNumOfFirstClassSeats(numOfFirstClassSeats);
        break;
    }
}
...




BookingSystem.java类:

// Instance variables.
private String[] stations = {"Lorem", "Ipsum", "Dolor", "Sit", "Amet", "Consectetur"};
private int[] numOfFirstClassSeats = {48, 48, 48, 48, 48};

public int[] getNumOfFirstClassSeats() {
    return this.numOfFirstClassSeats;
}

public void setNumOfFirstClassSeats(int[] numOfFirstClassSeats) {
    this.numOfFirstClassSeats = numOfFirstClassSeats;
}

public void printStations() {
    System.out.println("\n~ AVAILABLE SEATS ~");
    System.out.println("-------------------\n");

    String pattern = "%-20s %-20s %-21s %-23s %-20s\n";

    System.out.printf(pattern, "DEPARTING", "ARRIVING", "FIRST CLASS", "STANDARD CLASS", "EXCURSION CLASS");
    System.out.println("-------------------------------------------------------------------------------------------------------");
    for (int i = 0; i < 5; i++) {
        System.out.format(pattern, stations[i], stations[i + 1], getNumOfFirstClassSeats()[i], getNumOfStandardSeats()[i], getNumOfExcursionSeats()[i]);
    }
}


问题1:当我运行代码以预​​订头等舱座位时,如果登机点为“ Lorem”且目的地为“ Ipsum”,则代码仅更改“ Lorem”和“ Ipsum”的可用座位。

如果将登机点选择为“ Lorem”,而目的地是“ Sit”,则输出为:Index -2 out of bounds for length 5.

问题2:如果我有5位乘客,并且“ Lorem”是登机点,而“ Amet”是目的地,我希望将可用座位减少到“ Lorem”到“ Amet”的43位乘客。

我该如何完成?谢谢您的帮助!

最佳答案

对于问题1,请发布整个代码。

问题2:

这只是发人深省的冲动。

我会这样:

        System.out.println(Arrays.toString(numOfFirstClassSeats));
        for(int i=0; i<numOfFirstClassSeats.length; i++){
            if((destinationPoint >= i)&(boardingPointNum <= i)){
                numOfFirstClassSeats[i] = numOfFirstClassSeats[i]-1;
            }
        }
        System.out.println(Arrays.toString(numOfFirstClassSeats));


但是,如果需要,您必须添加一些安全性。如果你只去一个车站
boardingPointNum = destinationPoint

关于java - 改变数组的多个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60788832/

10-12 19:25