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

时间:2015-11-12 22:37:20

标签: java if-statement while-loop boolean

该程序是使用OOP的标准飞行数据库。在这个主要方法中,有5个选项执行不同的任务。选项1和2可以正常工作,但由于某些原因,选项3-5不会执行。选项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;
  }
}

1 个答案:

答案 0 :(得分:0)

对每种情况的选择使用switch()语句。喜欢

switch(x) {
    case 1:
        doSomething1();
    case 2:
        doSomething2();
    case 3:
        doSomething3();
}
相关问题