【问题标题】:Testing for input accuracy using a scanner with while and nested if/else statements使用带有 while 和嵌套 if/else 语句的扫描仪测试输入准确性
【发布时间】: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


【解决方案1】:

您在开头输入的输入值不会改变您以后输入的任何内容。 解决方案: 您需要使用input = scan.nextInt(); 而不是scan.nextInt(input);

希望我有所帮助! :)

【讨论】:

    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多