[英]Switch and loop while in Java
關於我的switch
我需要你的幫助。
下面是一個例子:
1) 我輸入選項 1
*****MENU*****
1) Start Play :
2) Exit :
Enter your choice : 1
2) 我輸入數字 4
You have 5 attemps.
Enter your number : 4
Bravo !
3)我贏了!
又想玩了。。。
我在選項 1 中輸入數字 1。
Bravo !
*****MENU*****
1) Start Play :
2) Exit :
Enter your choice : 1
在這里,我有一個問題......我無法進入選項1然后播放???
我總是有這個:
Enter your choice : 1
Option 1 :
*****MENU*****
1) Start Play :
2) Exit :
Enter your choice :
我認為我的問題是在我的case 1
?
int choice_user = 0;
int number_to_search = 4;
int number_user = 0;
boolean number_found = false;
int attemps = 5;
do {
System.out.println("*****MENU*****");
System.out.println("1) Start Play : ");
System.out.println("2) Exit : ");
System.out.print("Enter your choice : ");
choice_user = sc.nextInt();
switch (choice_user) {
case 1:
System.out.println("Option 1 : ");
while (number_to_search > 0 && !number_found) {
System.out.println("You have " + attemps + " attemps.");
System.out.print("Enter your number : ");
number_user = sc.nextInt();
if (number_user > number_to_search) {
System.out.println("Smallest ! ");
} else if (number_user < number_to_search) {
System.out.println("Biggest ! ");
} else {
number_found = true;
System.out.println("Bravo ! ");
}
attemps--;
}
break;
default:
System.out.println("Exit...");
}
} while (choice_user != 2);
您的代碼邏輯存在一些問題。
主要問題,以及為什么它在第一次迭代后繼續循環而不改變的原因是因為您沒有將number_found
的值重置為下一場比賽的false
。
此外,您需要將attemps
重置為5
,並檢查while (attemps > 0)
,而不是number_to_search
,后者不會改變。
更改后的代碼如下所示:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int choice_user = 0;
int number_to_search = 4;
int number_user = 0;
do{
System.out.println("*****MENU*****");
System.out.println("1) Start Play : ");
System.out.println("2) Exit : ");
System.out.print("Enter your choice : ");
choice_user = sc.nextInt();
int attemps = 5;
boolean number_found = false;
switch(choice_user){
case 1 :
System.out.println("Option 1 : ");
while(attemps > 0 && !number_found){
System.out.println("You have " + attemps + " attemps.");
System.out.print("Enter your number : ");
number_user = sc.nextInt();
if(number_user > number_to_search){
System.out.println("Smallest ! ");
}
else if(number_user < number_to_search){
System.out.println("Biggest ! ");
}
else{
number_found = true;
System.out.println("Bravo ! ");
}
attemps--;
}
break;
default:
System.out.println("Exit...");
}
}while(choice_user != 2);
}
注意我如何移動int attemps = 5;
和boolean number_found = false;
進入do-while
循環。 我測試了代碼,現在它似乎對我來說工作正常。
案例 1 完成后,您忘記再次將 number_found 設置為 false ,因此再次輸入時,您將跳過 while 循環,因為 number_found 仍為 true 。 您只需要在案例 1 的開頭執行 number_found = false 即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.