【问题标题】:How to repeat if statements in while loops [closed]如何在while循环中重复if语句[关闭]
【发布时间】:2019-02-17 09:36:18
【问题描述】:

我试图让用户猜测随机数生成器选择的数字,但我的代码决定,如果它不等于,则坚持一个 if 语句。

   System.out.println("Enter a guess between 1 and 200: ");
    String guess = input.nextLine();
    int userInput = Integer.parseInt(guess);

    Random rnd = new Random(seed);

    int x = rnd.nextInt(200) + 1;
    int currentInt = 1;
    String msg = "That was impossible!";

我的 while 循环包含许多 if 语句:

boolean boo = false;
while (!boo) {

        if (userInput == x) {
            System.out.println("Congratulations! Your guess was correct!");
            System.out.println("");
            System.out.println("I had chosen " + x + " as the target number.");
            System.out.println("You guessed it in " + currentInt + " tries.");

            if (currentInt == 1) {
                //do something
            } else if (currentInt >= 2) {
                //do something
            } else if (currentInt >= 4) {
                ...
            } else if (currentInt >= 11) {
                msg = "Maybe you should play something else";
                System.out.println(msg);
            }
            break;
        } else if (userInput > x) {
            System.out.println("Your guess was too high - try again.");
            System.out.println("");
            System.out.println("Enter a guess between 1 and 200: ");
            String highGuess = input.nextLine();
            int tooHigh = Integer.parseInt(highGuess);
            continue;
        } else if (userInput < x) {
            System.out.println("Your guess was too low - try again.");
            System.out.println("");
            System.out.println("Enter a guess between 1 and 200: ");
            String lowGuess = input.nextLine();
            int tooLow = Integer.parseInt(lowGuess);
            continue;
        }
        currentInt = currentInt + 1;

    }

我的代码运行良好,如果第一次尝试的答案是正确的,那么第一个 if 语句有效,但如果它大于或小于 x,则运行相同的块(如果更大,即使下一个输入是小于)

【问题讨论】:

  • 你永远不会更新 userInput,每个新的猜测都应该进入 userInput(或者“猜测”会是一个更好的名字)
  • 投票结束是一个印刷/微不足道的错误

标签: java if-statement while-loop


【解决方案1】:

tooHightooLow 更新userInput

【讨论】:

  • 我在做“tooLow = userInput;”和“太高 = 用户输入;”并且仍然得到相同的结果
  • @BrendonBaughn 另一种方式:userInput = tooLow
  • 现在可以了!谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-04-20
  • 2015-05-19
  • 2020-09-19
  • 2015-12-28
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多