简体   繁体   English

如果条件为真,则继续 while 循环

[英]continue a while loop if a condition is true

I have a guessing game program in which you have 4 attempts to guess a number between 0 and 9. I want to add an option where the program asks the user if they want to play again when the user exceeds his 4 attempts.我有一个猜谜游戏程序,您有 4 次尝试猜测 0 到 9 之间的数字。我想添加一个选项,当用户超过 4 次尝试时,程序会询问用户是否要再次玩游戏。 This is my code:这是我的代码:

public static void main(String[] args) {
    int nb, x;
    int count = 1;
    Scanner inp = new Scanner(System.in);
    nb = (int) (Math.random() * 10);

    System.out.print("Guess the number between 0 and 9 (4 Guesses allowed):");
    x = inp.nextInt();

    while (x != nb) {
        if (count <= 3) {
            if (x > nb) System.out.println("Lesser");
            else if (x < nb) System.out.println("Bigger");
            System.out.println("Wrong try another number");
            x = inp.nextInt();
            if (x == nb) System.out.println("Found!!");
        } else {
            System.out.print("you exceeded your allowed Guesses");
            break;
        }
        count++;
    }
    inp.close();
}

hope you (and everyone else) are staying healthy!希望您(和其他所有人)都保持健康!

Nested in your while loop, you have an if-else statement.嵌套在您的 while 循环中,您有一个 if-else 语句。 Here is where I suggest you make an addition.这是我建议您添加的地方。 Inside the else branch, I would output your desired message, and then handle user input: if the user says yes, reset your count integer to zero;在 else 分支中,我会输出您想要的消息,然后处理用户输入:如果用户说是,则将您的计数整数重置为零; the while loop will restart and you will be able to continue guessing. while 循环将重新启动,您将能够继续猜测。 If the user says no, I would execute the break statement just as you do right now.如果用户说不,我会像你现在一样执行 break 语句。 Hope this helps!希望这可以帮助!

Looks like a good candidate to make use of separate methods with.看起来是一个很好的候选者,可以使用单独的方法。 Move your current loop to another method, then make another loop inside your main method that calls your newly made method and prompts for a replay when the player returns after that run.将当前循环移动到另一个方法,然后在 main 方法中创建另一个循环,该循环调用新创建的方法并在播放器运行后返回时提示重播。

Partial code example:部分代码示例:

public static void main(String[] args) {
  Scanner inp = new Scanner(System.in);
  boolean play = true;
  while(play) {
    runGame(inp);
    System.out.println("Play again?");
    play = inp.nextLine().toUpperCase().contains("YES");
  }
  inp.close();
}

public static void runGame(Scanner inp) {
  int count = 1;
  //Move your current loop stuff here
}

Solution解决方案

At the end of your control flow, either where you guess the correct answer or you exceed the number of guesses , you need to prompt the user for an input.在控制流结束时,无论是您猜到了正确答案还是超过了猜测次数,您都需要提示用户进行输入。

Perhaps something along the lines of: "Do you wish to try again?"也许是这样的:“你想再试一次吗?”

You can do this using the scanner library, you can read about it and implement it from here .您可以使用扫描器库来执行此操作,您可以从此处阅读并实施它。

If they type "yes" (beware of case)如果他们输入“是” (注意大小写)

Assign nb = (int) (Math.random() * 10);分配nb = (int) (Math.random() * 10); again and validate it's not the same value as previously.再次验证它与以前的值不同。 This will cause the loop to keep running and thus the game continues.这将导致循环继续运行,从而游戏继续。

Note: It is important that if the same number appears again you handle it so to not terminate the game.注意:重要的是,如果再次出现相同的数字,请处理它以免终止游戏。 You can do this by getting another random number != to the previous one, or excluding that previous number from your random number pool so the selection is guaranteed to be different.您可以通过获取另一个随机数 != 到前一个,或从您的随机数池中排除该前一个数字来确保选择不同。

Additionally, I would advise you to give your variables a better name for readability, and formatting your code better, for the same reason.此外,出于同样的原因,我建议您为变量提供更好的名称以提高可读性,并更好地格式化代码。

I hope this helps.我希望这有帮助。

with just a minor tweak this will get you going.只需稍作调整,这将使您继续前进。

    public static void main(String[] args) {
int nb, x=-1;
int count = 0;
Scanner inp = new Scanner(System.in);
nb = (int) (Math.random() * 10);


while (x != nb) {
    System.out.print("Guess the number between 0 and 9 (4 Guesses allowed):");
    x = inp.nextInt();
        inp.nextLine();
         count++;
    if (x == nb){ System.out.println("Found!!");break;}
    if (x > nb) System.out.println("Lesser");
        else if (x < nb) System.out.println("Bigger");
        System.out.println("Wrong try another number");

    if (count == 2) {


        System.out.println("you exceeded your allowed Guesses");
        System.out.println("would you like to play again? (input y or n)");
        String newGame = inp.next();
               inp.nextLine();

        if(newGame.compareTo("n")==0)break;
        else count = 0;  

    }

}
inp.close();
}
}
public static void main(String... args) {
    final int min = 0;
    final int max = 10;
    final int maxGuesses = 4;

    try (Scanner scan = new Scanner(System.in)) {
        while (true) {
            final int expected = min + new Random().nextInt(max + 1 - min);
            boolean found = false;

            System.out.printf("Guess the number between %d and %d (%d Guesses allowed).\n", min, max, maxGuesses);

            for (int i = 1; i <= maxGuesses; i++) {
                System.out.printf("Guess #%d: ", i);
                int number = scan.nextInt();

                if (number == expected) {
                    found = true;
                    break;
                }

                System.out.println(number > expected ? "Lesser" : "Bigger");

                if (i < maxGuesses)
                    System.out.println("Wrong try another number");
            }

            System.out.println(found ? "Found!!" : "you exceeded your allowed Guesses");

            System.out.print("Do you want to continue (Y/N): ");
            char ch = scan.next().charAt(0);

            if (Character.toLowerCase(ch) == 'N')
                break;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM