首页 > 解决方案 > 如何在while循环中重复if语句

问题描述

我试图让用户猜测随机数生成器选择的数字,但我的代码决定,如果它不等于,则坚持一个 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,则运行相同的块(如果更大,即使下一个输入小于,也会保持更大)

标签: javaif-statementwhile-loop

解决方案


userInputtooHigh和更新tooLow


推荐阅读