我想写一个程序,随机生成一个数字,用户试图猜测数字。该程序会记录猜测正确数字的次数。我遇到的问题是越过while
循环。当我运行该程序时,它不会超过while
循环,直到我点击-1
,在这种情况下,它会输出"Your number is too low"
。我不确定我错在哪里。虽然循环和嵌套,如果语句
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args)
{
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
}
while(userInput != -1);
{
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
System.out.println("The number of tries: " + tries);
}
}
你的确.... ....循环语法不正确。 – victor
我不相信代码编译。你确定你把它正确地复制了吗? – victor
while循环使用While循环。 https://en.wikipedia.org/wiki/Do_while_loop –