【问题标题】:make a booking - For loop进行预订 - For 循环
【发布时间】:2014-03-16 18:37:51
【问题描述】:

我不确定我是否正确地执行了 for 循环以在 if 语句中给出一个真实的值。 如果我需要使用这种 for 循环,我如何增加 1。这是我正在研究的部分。

要进行预订,应提示用户输入他们希望旅行的目的地和星期几。如果存在这样的航班并且航班上有可用座位,则应输入乘客详细信息并创建新乘客。为该航班预订的座位数应加 1。

    public void flightBooking(){

    Passenger passenger;
    String    flightDay, flightDestination;
    boolean   found = false;
    Flight    myFlight = null;
    Scanner   scan = new Scanner(System.in);


    System.out.println(" On which day do you wish to travel ? ");
    flightDay = scan.nextLine();

    System.out.println(" What is your destination ? ");
    flightDestination = scan.nextLine();


    for ( Flight d  : flightList ) 
    {
        if (d.getDay().equals(flightDay))
        {
            myFlight= d;
            found = true;
        }

    }

    for ( Flight s  : flightList )
    {
        if (s.getDestination().equals(flightDestination))
        {
            myFlight= s;
            found = true;
        }

    }


    if (found == true)
    {
        System.out.println("The Flight Day and Destination were found, the Flight will be booked.");
        Passenger passengers = new Passenger ("Laura", "14 Rathmines Rd ","laura99@gmail.com" , myFlight);
        passengerList.add(passengers);

    }
    else
    {
        System.out.println("There is no flight booking.");
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    这是优化后的代码

    public void flightBooking(){
    
     Passenger passenger;
     String    flightDay, flightDestination;
     boolean   found = false;
     Flight    myFlight = null;
     Scanner   scan = new Scanner(System.in);
    
    
     System.out.println(" On which day do you wish to travel ? ");
     flightDay = scan.nextLine();
    
     System.out.println(" What is your destination ? ");
     flightDestination = scan.nextLine();
    
    
     for ( Flight d  : flightList ) 
     {
        if (d.getDay().equals(flightDay) && d.getDestination().equals(flightDestination))
        {
            System.out.println("The Flight Day and Destination were found, the Flight will be booked.");
        Passenger passengers = new Passenger ("Laura", "14 Rathmines Rd ","laura99@gmail.com" , myFlight);
        passengerList.add(passengers);
            found = true;
            break;
        }
    
     }
    
     if (found == false)
     {
    
        System.out.println("There is no flight booking.");
     }
    }
    

    在您的代码中,如果日期不匹配且目的地匹配,那么预订也会发生,因为添加两个 for 循环正在生成它或条件,但它应该是 and。也只能通过一个for循环来实现。

    【讨论】:

    • 我认为您还需要将break 放入if 循环内的for-each 语句中。否则,它可能会将乘客添加到多个航班。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多