简体   繁体   中英

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. 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. 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; the while loop will restart and you will be able to continue guessing. If the user says no, I would execute the break statement just as you do right now. 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.

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); 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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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