【发布时间】:2016-02-23 07:38:39
【问题描述】:
当我尝试在 while 循环之外使用“exit”(8) if 语句时,如何防止显示子菜单?目前,当我输入 8 时,它会显示子菜单,然后说退出,并执行它所在的测试器类的其余功能。
mainMenu.addOption("Add Item"); // creating menu
mainMenu.addOption("Remove Item");
mainMenu.addOption("");
mainMenu.addOption("");
mainMenu.addOption("");
mainMenu.addOption("");
mainMenu.addOption("");
mainMenu.addOption("Exit");
subMenu.addOption("Burger");
subMenu.addOption("Drink");
subMenu.addOption("Fries");
int input;
int choice;
do{
input = mainMenu.getInput();
choice = subMenu.getInput();
if(input == 1){
if(choice == 1){
System.out.println("Burger Added");
}
if(choice == 2){
System.out.println("Drink Added");
}
if(choice == 3){
System.out.println("Fries Added");
}
}
if(input == 2){
if(choice == 1){
System.out.println("Burger Removed");
}
if(choice == 2){
System.out.println("Drink Removed");
}
if(choice == 3){
System.out.println("Fries Removed");
}
}
} while(input != 8);
if(input == 8){
//choice = 8;
System.out.println("exiting");
}
这是菜单类
import java.util.ArrayList;
import java.util.Scanner;
/**
A menu that is displayed on a console.
*/
public class Menu
{
// Declare instance variables ****
// Global
private ArrayList<String> options;
private Scanner in;
/**
Constructs a menu with no options.
*/
public Menu()
{
/* Constructor - a special method whose name matches the class name exactly. Takes no or many arguments
* no return type for constructors
* purpose is to initialize data variables
*/
options = new ArrayList<String>();
in = new Scanner(System.in);
}
/**
Adds an option to the end of this menu.
@param option the option to add
*/
public void addOption(String option)
{
options.add(option);
}
/**
Displays the menu, with options numbered starting with 1,
and prompts the user for input. Repeats until a valid input
is supplied.
@return the number that the user supplied
*/
public int getInput()
{
int input;
do
{
for (int i = 0; i < options.size(); i++)
{
int choice = i + 1;
System.out.println(choice + ") " + options.get(i));
}
input = in.nextInt();
}
while (input < 1 || input > options.size());
return input;
}
}
【问题讨论】:
-
您应该研究
if-then-else语句及其相对于使用多个if-then语句的好处(在某些情况下)。 The if-then and if-then-else Statements -
与问题无关
-
如果您仔细研究过它,您应该会看到另一种编写程序的方式。您的问题的答案:使用
while循环而不是do-while并让它检查input != 8。无论条件如何,do-while循环至少迭代一次。 -
不会导致无限循环
-
我会发布一个答案以更清楚地显示它。