【问题标题】:Problems with if/else statements nested in a while loop嵌套在 while 循环中的 if/else 语句的问题
【发布时间】:2016-02-14 10:40:48
【问题描述】:

该程序是使用 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;
  }
}

【问题讨论】:

  • 你能附上输出块吗?
  • 您输入输入选项时是否有特定的顺序?如果在 3、4.或 5 之前执行 1 和或 2,或者如果您先输入 3、4 或 5,这两种情况下是否仍会出现问题?
  • 您要打印哪个航班(1 或 2)? 1 航班名称:A 目的地:纽约出发时间:A1 出发口:上午 11:00 现在您想做什么? 1. 打印出航班信息 2. 通过静态变量打印出航班数量 3. 更改航班的起飞时间 4. 更改航班的登机口 5. 出口 3 您想更改哪个航班的起飞(1或2)的时间?现在你想做什么? 1. 打印出航班信息 2. 通过静态变量打印出航班数量 3. 更改航班起飞时间等。@ADi
  • 无论顺序如何,问题仍然存在。我认为这可能与选项 3、4 和 5 的扫描仪有关? @DBug
  • 我将它剪切/粘贴到一个小测试程序中,所有 5 个选项都正常工作。您可能需要展示整个程序(如果不是太大)。

标签: java if-statement while-loop boolean


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2017-02-06
  • 2023-03-30
  • 1970-01-01
  • 2012-03-12
  • 2020-06-22
  • 2015-12-28
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多