【发布时间】:2017-12-03 12:57:08
【问题描述】:
所以我尝试使用 while 循环继续请求输入,而用户输入的随机数不等于随机数生成器的输出。但是,当我输入数字时,较高/较低的输出不起作用。无论实际数值如何,它要么总是说它更高,要么总是说它更低。帮助?
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:docs.oracle.com/javase/8/docs/api/java/util/…。这看起来像你想做的吗?你第一次就做对了。为什么不在循环内做同样的事情?
标签: java if-statement while-loop