[英]Looping through a switch statement
因此,我正在编写一个基于菜单的程序,并且陷入其中。 这是我的代码:
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。
一个简单的选择是声明一个布尔变量并将switch
包装在while循环中,例如
Boolean quit = false;
while (!quit) //or do-while
{
int opt = menu();
switch(opt)
{
//other cases...
case 4:
quit = true;
}
}
我不确定为什么在每种情况下都要调用菜单。
我不是用Java编写代码,而是尝试在每种情况的结尾将其指向默认情况,以便在程序完成操作后将默认返回菜单。
对于菜单,我总是将菜单选项和请求包装在do-while循环中。
do{
menu code...
} while (menu() != 4);
您可以将代码保持在无限循环中,并在按下4
时退出程序。 不需要在所有情况下都调用menu()
,因为每次迭代中仅显示一个菜单。
进行无限循环使用
while(true) {
//some code
}
用于退出程序使用:
System.exit(0);
尝试这个 :
while(true) {
int choice = menu();
switch (choice) {
case 1:
System.out.println("Stub 1");
break;
case 2:
System.out.println("Stub 2");
break;
case 3:
System.out.println("Stub 3");
break;
case 4:
System.out.println("Program Terminated");
System.exit(0); // for terminating the program
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.