0
因此,我試圖使用while循環繼續詢問輸入,而用戶輸入的隨機數不等於隨機數生成器的輸出。但是,當我輸入數字時,高/低輸出不起作用。無論實際數值如何,它總是說它更高或總是說低。幫幫我?使用帶有while和嵌套if/else語句的掃描儀測試輸入精度
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int rand1 = rand.nextInt(MAX);
introduction();
game(scan, rand1);
}
public static void introduction() {
System.out.println("This program allows you to play a guessing game."
" I will think of a number between 1 and" +
" 100 and will allow you to guess until" +
" you get it. For each guess, I will tell you" +
" whether the right answer is higher or lower" +
" than your guess");
}
public static void game(Scanner scan, int rand1) {
System.out.println("I'm thinking of a number between 1 and 100...");
System.out.println(rand1);
System.out.println("Your guess?");
int input = scan.nextInt();
while(input != rand1) {
if (input < rand1) {
System.out.println("It's higher");
scan.nextInt(input);
}
else if (input > rand1) {
System.out.println("It's lower");
scan.nextInt(input);
}
}
}
}
下面是您用於讀取下一個int並更改循環內輸入值的方法的javadoc:https://docs.oracle.com/javase/8/docs/api/java/ UTIL/Scanner.html#nextInt,內部 - 。這看起來像你想要做的?你第一次做對了。你爲什麼不在循環內部做同樣的事情? –