在Java上使用数组进行席位预留的想法

时间:2017-10-14 01:28:13

标签: java arrays

如您所知,Java的数组从零开始。在谈论巴士座位时,您可能会想到一系列座位。例如,9个座位。

Here is a preview of the array

我有这个问题,因为顾客不会要求座位0(起始座位),他们会要求“第一”座位(座位号码1)。因此,如果他们输入(1)作为所需的座位(对于客户来说它将是第一个),该方法将“保留”第二个阵列的字段,因为第一个是零。所以,我不知道如何解决这个问题。

public void occupySeat(int seat) {
        Seats[seat] = true;
} /* This is the reservation method

我的想法是,我可以输出一条消息,说他们可以保留的第一个座位是零。等等。所以最后一个是第八个。但这让我不满意。

任何想法都会很棒!谢谢。

3 个答案:

答案 0 :(得分:1)

这是一种非常常见的模式,请尝试

public void occupySeat(int seat) {
    Seats[seat-1] = true;
} 

并且可能确保他们输入有效的整数:)

答案 1 :(得分:0)

public void occupySeat(int seat) {
        Seats[seat-1] = true;
} /* This is the reservation method

根据需要添加和减去1。

答案 2 :(得分:0)

您可以使用Map代替。

通过这种方式,您可以有更多机会在您的座位集中进行更多操作。

private Map<Integer, Seat> seats = new HashMap<>();

public void occupySeat(int seat) {
   seats.put(seat, true);
} /* This is the reservation method