我想創建一個數字猜測程序,用戶輸入一個數字,程序會告訴您輸入是否太高,太低或正確。程序選擇0-100之間的隨機數。問題是,當我開始測試程序時,當我選擇1時,程序告訴我猜測過高。但是這是錯誤的,因爲程序只能做整數。如果用戶輸入的號碼不等於隨機數,則1必須太低。 有人可以看看我的代碼,看看是否有什麼奇怪的。數字猜測程序錯誤?
int guess;
int guess2;
int guess3;
int guess4;
int guess5;
int random = (int)Math.random() * 100;
Scanner input = new Scanner(System.in);
System.out.println("Try to guess a number between 0-100. You have five chances.");
guess = input.nextInt();
if(guess >= 100 || guess <= 0){
System.out.println("Error, that is not a number between 0-100.");
} else if(guess > random){
System.out.println("The guess is too high.");
} else if(guess < random){
System.out.println("The guess is too low.");
} else if(guess == random){
System.out.println("YOU WIN");
} else{
}
System.out.println("Second guess.");
guess2 = input.nextInt();
if(guess2 >= 100 || guess2 <= 0){
System.out.println("Error, that is not a number between 0-100.");
} else if(guess2 > random){
System.out.println("The guess is too high.");
} else if(guess2 < random){
System.out.println("The guess is too low.");
} else if(guess2 == random){
System.out.println("YOU WIN");
} else{
}
System.out.println("Third guess.");
guess3 = input.nextInt();
if(guess3 >= 100 || guess3 <= 0){
System.out.println("Error, that is not a number between 0-100.");
} else if(guess3 > random){
System.out.println("The guess is too high.");
} else if(guess3 < random){
System.out.println("The guess is too low.");
} else if(guess3 == random){
System.out.println("YOU WIN");
} else{
}
System.out.println("Fourth guess.");
guess4 = input.nextInt();
if(guess4 >= 100 || guess4 <= 0){
System.out.println("Error, that is not a number between 0-100.");
} else if(guess4 > random){
System.out.println("The guess is too high.");
} else if(guess4 < random){
System.out.println("The guess is too low.");
} else if(guess4 == random){
System.out.println("YOU WIN");
} else{
}
System.out.println("Last guess.");
guess5 = input.nextInt();
if(guess5 >= 100 || guess5 <= 0){
System.out.println("Error, that is not a number between 0-100.");
} else if(guess5 > random){
System.out.println("The guess is too high.");
} else if(guess5 < random){
System.out.println("The guess is too low.");
} else if(guess5 == random){
System.out.println("YOU WIN");
} else{
}
所以「return」在if語句中結束程序? – Nocturne 2014-09-19 04:33:08
返回標記方法的結束。在這種情況下,你在程序的主要方法main()中,所以它會結束程序。 – nostromo 2014-09-19 04:33:46
@nostromo你好嗎?只是友好的點你有沒有看到這條線?如果(guess2> = 100 || guess2 <= 0){它在0和100之間嗎? – 2014-09-19 04:36:01