[英]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.