所以我正在编写一个基于菜单的程序,但我陷入了一个部分。这是我的代码:
public static void main(String [] args) throws FileNotFoundException {
switch (menu()) {
case 1:
System.out.println("Stub 1");
menu();
break;
case 2:
System.out.println("Stub 2");
menu();
break;
case 3:
System.out.println("Stub 3");
menu();
break;
case 4:
System.out.println("Program Terminated");
break;
}
}
public static int menu() {
System.out.println("Choose a task number from the following: ");
System.out.println("\t1. - See histogram of name's popularity");
System.out.println("\t2. - Compare two names in a specific decade");
System.out.println("\t3. - Show what name had a specific rank for a certain decade");
System.out.println("\t4. - Exit program");
int opt = 0;
int option = getInt(input,"Enter number (1-4): ", 1, 4);
if (option == 1) {
opt = 1;
}
else if (option == 2) {
opt = 2;
}
else if (option == 3) {
opt = 3;
}
else {
opt = 4;
}
return opt;
}
我的问题是,按下选项后如何使菜单“重置”。例如,我选择 1,程序执行该操作,完成后,它会再次显示选项菜单,直到我按 4 终止它。
我的代码中的 getInt
方法仅返回 1 到 4 之间的 int。
最佳答案
一个简单的选择是声明一个 boolean 变量并将switch
包装在一个while循环中,例如
Boolean quit = false;
while (!quit) //or do-while
{
int opt = menu();
switch(opt)
{
//other cases...
case 4:
quit = true;
}
}
我不确定为什么你在每种情况下都调用菜单。
关于java - 循环遍历 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27073299/