public class GuessingGame {
public static void main(String[] args){
double randomNumber = Math.floor((Math.random()*100)+1);
Scanner userInputScanner = new Scanner(System.in);
do {
System.out.println("Enter your guess");
System.out.println("\n");
int Guess = userInputScanner.nextInt();
if(Guess == randomNumber)
System.out.print("Good");
System.out.print("\n");
else if(Guess < randomNumber)
System.out.print("Higher");
System.out.println("\n");
else if(Guess > randomNumber)
System.out.print("Lower");
System.out.println("\n");
}
while(Guess != randomNumber);
}
}
答案 0 :(得分:2)
在if和if body下添加括号{}
,Java在if else和indentation中不像python一样工作
if(Guess == randomNumber) {
System.out.print("Good");
System.out.print("\n");
} else if(Guess < randomNumber) {
System.out.print("Higher");
System.out.println("\n");
} else if(Guess > randomNumber) {
System.out.print("Lower");
System.out.println("\n");
}
答案 1 :(得分:1)
应该是这样的:
if(Guess == randomNumber){
System.out.print("Good");
System.out.print("\n");
}else if(Guess < randomNumber){
System.out.print("Higher");
System.out.println("\n");
}else if(Guess > randomNumber){
System.out.print("Lower");
System.out.println("\n");}
围绕if-else括号。
答案 2 :(得分:1)
问题是您是否尝试将多个语句放在if
块中而没有花括号。在其他语言中,缩进控制结构,但Java是自由格式的,因此没有大括号,只有一个语句被分组到每个if
/ else
。
所以程序将第一个语句分组到if
,然后下一个语句是单独的,那么你有一个else
没有前一个if
。
答案 3 :(得分:1)
你需要在每个if条件之后添加{}
,并且在执行while之前需要声明Guess变量
在这里完整的代码,已经编译并且没有错误
import java.util.Scanner;
public class GuessingGame{
public static void main(String[] args){
double randomNumber = Math.floor((Math.random()*100)+1);
Scanner userInputScanner = new Scanner(System.in);
int Guess = 0;
do{
System.out.println("Enter your guess");
System.out.println("\n");
Guess = userInputScanner.nextInt();
if(Guess == randomNumber) {
System.out.print("Good");
System.out.print("\n");
}
else if(Guess < randomNumber) {
System.out.print("Higher");
System.out.println("\n");
}
else if(Guess > randomNumber) {
System.out.print("Lower");
System.out.println("\n");
}
}
while(Guess != randomNumber);
}
}