我正在创建一个生成随机数的程序,您猜不到,然后告诉您是否正确。代码是:
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.nextLine();
If (userGuess = randomNumber); {
numberOfTries += 1;
System.out.println("Correct! It took you " + numberOfTries + " tries to find my numnber");
} Else; {
distanceFromNumber = Math.abs(7);
numberOfTries += 1;
System.out.println("Incorrect! The number that you guessed is " + distanceFromNumber + "numbers away from my number ");
}
}
编译器返回“Else”部分不是语句。如果我从“If”和“Else”行中删除分号,编译器还会告诉我这两行是期望';'。我也尝试改变括号的格式,这没有帮助。
答案 0 :(得分:2)
否则应该是小写,就像Java中的所有关键字一样,不应该以分号结尾
...
} else {
...
在if()或while()语句之后也不应该有一个分号,而你的while()语句后面没有开括号,即
while(true)
{ //missing
}
总之,另外
void guessNumber() //EDIT removed semi-colon
{
//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) //EDIT removed semi-colon + lowercase while
{//EDIT added this bracket
System.out.println("Guess the number ");
int userGuess = reader.nextLine();
if (userGuess == randomNumber) {//EDIT removed semi colon, lowered case of 'If' & added double equals (equality testing and not assignment)
numberOfTries += 1;
System.out.println("Correct! It took you " + numberOfTries + " tries to find my numnber");
} else { //EDIT removed semi-colon & changed case
distanceFromNumber = Math.abs(7);
numberOfTries += 1;
System.out.println("Incorrect! The number that you guessed is " + distanceFromNumber + "numbers away from my number ");
}
}//EDIT Added this bracket
}
答案 1 :(得分:1)
你正在使用大写字母,特殊字总是在小写
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.nextLine();
if (userGuess = randomNumber) {
numberOfTries += 1;
System.out.println("Correct! It took you " + numberOfTries + " tries to find my numnber");
} else {
distanceFromNumber = Math.abs(7);
numberOfTries += 1;
System.out.println("Incorrect! The number that you guessed is " + distanceFromNumber + "numbers away from my number ");
}
}
答案 2 :(得分:0)
java中的关键字是低级的(while
,if
,else
...)
您还希望在;
,while
和if
行之后删除else
。
为了比较值,请使用:
if (userGuess == randomNumber) {
答案 3 :(得分:0)
If (userGuess = randomNumber)
应该是
If (userGuess == randomNumber)
答案 4 :(得分:0)
所有java关键字都应该是小写的,所以;
if
else
while
另外你使用==来提问是等于其他东西的问题,而不是= 设置等于其他东西。
所以
while(condition){
if (a==b){
}else{
}
}