[英]Java - two do while Loops not working with scanner
import java.util.Scanner;
public class doWhileLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Guess a number between 1 and 10:");
int val = input.nextInt();
do
{
System.out.println("Guess Again!");
val = input.nextInt();
}
while(val != 5);
do
{
System.out.println("Stop messing around!");
val = input.nextInt();
}
while(val < 1 || val > 10);
if(val == 5)
{
System.out.println("Nice guess!");
}
}
}
我不確定這段代碼有什么問題,我嘗試了很多方法來改變它,但它只是沒有按照我想要的方式運行。 如果用戶輸入除 5 以外的任何內容,那么它會說“再猜一次”,即使它超過 10 或小於 1,但直到用戶輸入 5,它是否會說“停止亂搞!”,那么如果我再次輸入 5,然后它說“很好的猜測”。
使用 do-while 語句,您執行 do 塊中的代碼一次,然后驗證 while 語句中的條件,因此如果您不想在驗證之前執行一次,我建議您使用 while 而不是 do-while。
也許像
…………
while(val != 5){
System.out.println("Guess Again!");
val = input.nextInt();
if(val < 1 || val > 10){
System.out.println("Stop messing around!");
val = input.nextInt();
}
}
if(val == 5)
{
System.out.println("Nice guess!");
}
......
會做預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.