我正在制作随机数生成器,然后让用户猜出数字。然后,计算机将告诉用户该号码是否正确以及猜测与虚拟号码的距离。当我编译:
public static void guessNumber()
{
//Asks for guess of the number. Prints whether the guess is above or below randomNumber.
Scanner reader = new Scanner(System.in);
numberOfTries = 0;
while(userGuess != randomNumber){
System.out.println("Guess the number ");
int userGuess = reader.nextInt();
if (userGuess == randomNumber) {
int numberOfGuesses++;
System.out.println("Correct! It took you " + numberOfTries + " tries to find my numnber");
} else {
int distanceFromNumber = Math.abs(randomNumber - userGuess);
int numberOfGuesses++;
System.out.println("Incorrect! The number that you guessed is " + distanceFromNumber + "numbers away from my number ");
}
}
我收到此错误:
C:\!!VHSJava\Projects\random.java:47: error: ';' expected
int numberOfGuesses++;
^
C:\!!VHSJava\Projects\random.java:51: error: ';' expected
int numberOfGuesses++;
^
我已经尝试将其更改为numberOfGuesses + = 1,但是出现了同样的错误。
答案 0 :(得分:0)
int numberOfGuesses++;
声明时不能增加值。
在
之前定义你的变量 int numberOfGuesses =0
稍后递增
numberOfGuesses++
答案 1 :(得分:0)
您需要先声明变量然后再使用它。两者都不能在同一个语句中一起完成,因为numberOfGuesses
甚至没有值来增加它。
int numberOfGuesses = 0; // declare it before the if
...
numberOfGuesses++; // use it in the if
答案 2 :(得分:0)
在更高级别的范围内声明整数,然后递增它:
int numberOfGuesses = 0;
//...
numberOfGuesses++;