简体   繁体   English

if / else语句嵌套在while循环中的问题

[英]Problems with if/else statements nested in a while loop

The program is a standard flight database using OOP. 该程序是使用OOP的标准飞行数据库。 In this main method there are 5 options that execute different tasks. 在此主要方法中,有5个执行不同任务的选项。 Options 1 and 2 work without a problem, but for some reason options 3-5 don't execute. 选项1和2可以正常工作,但是由于某些原因,选项3-5不会执行。 The code inside the if/else if's of options 3-5 do not run, and the program just outputs the main menu again. 选项3-5的if / else if中的代码不会运行,该程序仅会再次输出主菜单。

boolean exit = false;
while (exit == false)
{
  System.out.println("Now what would you like to do?");
  System.out.println("1. Print out a flight's info");
  System.out.println("2. Print out the number of flights through the static variable");
  System.out.println("3. Change the departure time of a flight");
  System.out.println("4. Change the departure gate of a flight");
  System.out.println("5. Exit");

  int choice = sc.nextInt();

  if (choice == 1)
  {
    System.out.println("Which flight would you like to print (1 or 2)?");
    int choice2 = sc.nextInt();
    if (choice2 == 1)
    {
      f1.printFlight();
    }
    else if (choice2 == 2)
    {
      f2.printFlight();
    }
    else
    {
      System.out.println("Invalid choice");
    }
  }

  else if (choice == 2)
  {
    System.out.println("This is the number of flights: ");
    int numFlights = f1.getNumFlights();
    System.out.println(numFlights);
  }

  else if (choice == 3)
  {
    System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
    int choice3 = sc.nextInt();
    System.out.println(choice3);

    if (choice3 == 1)
    {
      System.out.println("What is the new departure time for flight " + choice3);
      int newTime = sc.nextInt();
      f1.changeDeptTime(newTime);
    }

    else if (choice3 == 2)
    {
      f2.changeDeptTime();
    }

    else
    {
      System.out.println("Invalid choice");
    }
  }

  else if (choice == 4)
  {
    System.out.println("Which flight would you like to change the departure gate of (1 or 2)?");
    int choice4 = sc.nextInt();

    if (choice4 == 1)
    {
      f1.changeDeptGate();
    }

    else if (choice4 == 2)
    {
      f2.changeDeptGate();
    }

    else
    {
      System.out.println("Invalid choice");
    }
  }

  else if (choice == 5)
  {
    System.out.println("Exit Reached");
    exit = true;
  }
}

Use switch() statement for the choices for each case. 使用switch()语句选择每种情况。 Like 喜欢

switch(x) {
    case 1:
        doSomething1();
    case 2:
        doSomething2();
    case 3:
        doSomething3();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM