[英]Ending this do-while loop?
當用戶輸入 0 時如何結束 do-while 循環?
如果用戶輸入 F、G、H 和 J,程序將繼續執行。如果用戶輸入 0,程序將退出。
import java.util.Scanner;
public class P4Q5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\nMain Menu: \n" +
"Enter 0 to exit program\n" +
"Enter F to display Faith\n" +
"Enter G to display Grace\n" +
"Enter H to display Hope\n" +
"Enter J to display Joy\n");
do {
System.out.print("Enter your choice:");
String s = sc.nextLine();
char ch = s.charAt(0);
if (( ch == 'F')) {
System.out.println("\nFaith\n");
}
else if (( ch == 'G')) {
System.out.println("\nGrace\n");
}
else if (( ch == 'H')) {
System.out.println("\nHope\n");
}
else if (( ch == 'J')) {
System.out.println("\nJoy\n");
}
else {
System.out.println("\nWrong option entered!!\n");
}
} while (ch == 'O');
// TODO code application logic here
}
}
while (ch != '0')
而不是while (ch == 'O')
怎么樣? 注意0
和O
之間的區別?
在你做的時候試試這個:
if( ch == '0') break;
嘗試這個:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\nMain Menu: \n" +
"Enter 0 to exit program\n" +
"Enter F to display Faith\n" +
"Enter G to display Grace\n" +
"Enter H to display Hope\n" +
"Enter J to display Joy\n");
do {
System.out.print("Enter your choice:");
String s = sc.nextLine();
char ch = s.charAt(0);
if (( ch == 'F')) {
System.out.println("\nFaith\n");
}
else if (( ch == 'G')) {
System.out.println("\nGrace\n");
}
else if (( ch == 'H')) {
System.out.println("\nHope\n");
}
else if (( ch == 'J')) {
System.out.println("\nJoy\n");
}
else if (( ch == 'O' )) {
System.exit();
}
else {
System.out.println("\nWrong option entered!!\n");
}
} while (ch == 'F' || ch == 'G' || ch == 'H' || ch == 'J' || ch == 'O');
// TODO code application logic here
}
要退出程序,您需要執行 System.exit()
要退出循環,請按照@bitmask 所述操作
我會使用 boolean 變量,如果輸入 0,則 boolean 變為真,然后檢查 boolean...
boolean bool = false;
do {
...
if(input == '0')
bool=true;
} while (!bool);
哦,在我忘記之前,我還會在 do while 之前輸入一個輸入,在循環結束時輸入一個。 像這樣,您的整個代碼在您點擊 0 后將不會再次運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.