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!");
}
}
}
I am not sure what is wrong with this code, I have tried to change it many ways but it just does not run how i want it to. If the user enters anything but 5 then it says "guess again", even if it is over 10 or less than 1, but until the user enters 5, does it say "stop messing around!", then if I enter 5 again, then it says "Nice guess".
使用 do-while 语句,您执行 do 块中的代码一次,然后验证 while 语句中的条件,因此如果您不想在验证之前执行一次,我建议您使用 while 而不是 do-while。
maybe something like
........
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!");
}
......
will do the expected result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.