java - 使用用户输入迭代 While 循环

标签 java if-statement random while-loop user-input

首先,感谢您阅读我的帖子并为我提供帮助。

我正在尝试编程,在其中定义一个随机数,程序猜测这个随机数,然后根据我说的猜测是否太高或太低,程序再次猜测。

当程序猜测的数字太高时,用户应输入“lower”,然后程序仅猜测较低的数字。

理想情况下,程序会考虑之前所有选择的结果。因此,如果猜测#1 太高,则这应该仍然是之后所有迭代的上限。我们不希望每次迭代时只改变上限或下限。

我尝试对代码执行的操作是重置用于计算随机数( ThreadLocalRandom )的最小值和最大值。

主要问题是我无法重置 oMin 和 oMax 值。我不明白如何解决这个问题,很抱歉,如果这是一个完全愚蠢的问题。

再次感谢!

import java.util.Scanner;

import java.util.concurrent.ThreadLocalRandom;

public class J4AB_S11_C3 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int oMin = 0;
        int oMax = 101;
        int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
        String userReply;

        System.out.println("What's the lucky number, kiddo?");
        int correctAnswer = scanner.nextInt();

        System.out.println("Is " + randomNumber + " the right answer?");
        userReply = scanner.next();

        while ("Higher".equalsIgnoreCase(userReply)) {
            oMin = randomNumber;
        }

        while ("Lower".equalsIgnoreCase(userReply)) {
            oMax = randomNumber;
        }

        if (userReply.equalsIgnoreCase("Correct")) {
            System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
        }

    }
}

最佳答案

对此使用 do-while、if 条件来检查较高和较低。并在 do-while 后关闭 scanner

        Scanner scanner = new Scanner(System.in);
        int oMin = 0;
        int oMax = 101;
        String userReply;
        int correctAnswer;
        do {
            int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
            System.out.println("What's the lucky number, kiddo?");
            correctAnswer = scanner.nextInt();

            System.out.println("Is " + randomNumber + " the right answer?");
            userReply = scanner.next();

            if ("Higher".equalsIgnoreCase(userReply)) {
                oMin = randomNumber;
            }else if ("Lower".equalsIgnoreCase(userReply)) {
                oMax = randomNumber;
            }
        } while (!userReply.equalsIgnoreCase("Correct"));

        System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");

        scanner.close();

关于java - 使用用户输入迭代 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61966975/

相关文章:

java - 在 Java 11 App Engine 项目中配置静态文件 (CSS)

r - dplyr ifelse 语句中的嵌套条件

javascript - 从 JavaScript 数组中获取随机项

java - 如何将图像放入ListView javafx中

Java Graphics2d 使用证卡打印机将高分辨率图像打印到 CR80 卡中

java - 如何使用 stackexchange api 交叉检查技术技能(标签)?

css - PHP/HTML/CSS - 如果是 FireFox,是 Chrome 还是 Safari

javascript - 重构 if 语句以消除冗余

java - 在多线程的情况下使用流限制的最佳性能方式

c - C 问题中的新手随机数生成器?