continue a while loop if a condition is true

samer g :

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();
}
DCR :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=385745&siteId=1