【问题标题】:Using arrays inside if conditions在 if 条件中使用数组
【发布时间】:2020-11-20 16:18:24
【问题描述】:

此代码应该模拟机场的票务系统。

这段代码有 3 个不同的类: AirlineTicket,它包含在这个程序中创建的对象的构造函数、访问器和修改器; AirlineTicketTester,它创建一个对象和一个数组,并使用同一类中的一个方法用“乘客”填充该数组; TicketOrganizer 有两种方法,但只有一种方法很重要:canBoardTogether()。这个方法应该做的是检查数组中的乘客是否可以与以下乘客一起登机。这样做的条件是两个乘客都需要具有相同的登机组和行(AirlineTicket 类的两个属性)。但是,这个方法不能正常工作,它没有返回正确的可以一起登机的乘客。

我能做些什么来纠正上述方法? TicketOrganizer 类

import java.util.*;
public class TicketOrganizer
{
    private ArrayList<AirlineTicket> tickets;
    
    public TicketOrganizer(ArrayList<AirlineTicket> ticket){
        this.tickets = ticket;
    }
    
    public ArrayList<AirlineTicket> getTickets(){
        return tickets;
    }
       
        }
        public String canBoardTogether(){
            String together = "";
            int counter = 0;
            for(int i = 0; i<tickets.size()-1; i++){
                if(tickets.get(i).getBoardingGroup() == 
                tickets.get(i+1).getBoardingGroup()&&tickets.get(i).getRow() == 
                tickets.get(i+1).getRow()){
                together = together + "Passenger " + i + " can board with Passenger " + (int)(i+1) + "\n";
                counter++;
            }
        } 
            if(counter == 0){
            return "There are no passengers with the same row and boarding group.";
            }
            
            return together;
        

    }
    }

【问题讨论】:

  • 你能把问题出在哪里吗?没有人会读 3 节课
  • 您的票务信息有哪些类型? (字符串,整数)?
  • 票证信息的类型是int
  • 现在我看到了您要执行的操作,我认为您的代码没有问题。您应该打印出登机和机票信息,以确保它与您所相信的一致。
  • 最好同时查看实际输出和预期输出,这样我们就可以看到可能出了什么问题。

标签: java arraylist methods


【解决方案1】:

由于您只是比较 tickets.get(i)tickets.get(i+1),因此您的代码要求具有相同登机组和同一行的机票将在 tickets 列表中相邻

除非门票按登机组排序然后行,否则您的代码不一定会找到您期望的匹配项。

在进行搜索之前试试这个:

tickets.sort(comparing(AirlineTicket::getBoardingGroup).andThen(AirlineTicket::getRow));

【讨论】:

  • 我们已经介绍过了。我做了同样的假设。它们是相邻的。问题是数据是随机的,所以它不会总是按预期工作。
  • @WJS 我看不到这方面的报道——这个页面上没有其他地方的文本“排序”。鉴于 OP 的算法,预排序是必需的 - 没有办法解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2016-03-08
  • 2016-11-24
  • 2020-04-20
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
相关资源
最近更新 更多