使用带有while和嵌套if / else语句的扫描仪测试输入精度

时间:2017-06-29 17:36:38

标签: java if-statement while-loop

所以我试图使用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);
            }
         }
    }
}

1 个答案:

答案 0 :(得分:0)

您在开头输入的输入值不会随后更改您输入的内容。 解: 您需要使用input = scan.nextInt();           而不是scan.nextInt(input);

希望我帮助过! :)