adding a condition to a java code where user can only have 4 tries

Viewed 56

So I have this code where the user enters a random number from 0 to 9 and has to guess the number but I want to limit the users trials to 4 once he guessed wrong 4 times the system stops and displays a message "you exceeded your allowed trials" this is my code so far:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nb,x;
    int count= 0;
    Scanner inp= new Scanner(System.in);
    nb= (int)(Math.random()*10);
    System.out.print("Guess the number between 0 and 9");
    x=inp.nextInt();

    while(x!= nb) {
        if(x>nb) System.out.println("Lesser");
        else if (x<nb) System.out.println("Bigger");
        System.out.println("Try another Number");
        x=inp.nextInt();
        count++;

    }

    System.out.println("Found!!");
    System.out.println("Number of Guesses:" +count);


    inp.close();

}
3 Answers

You can also used you count variable to keep track of attempts, once user ends with limit you can exit the program by breaking the while loop using break statement.

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nb,x;
    int count= 1;
    Scanner inp= new Scanner(System.in);
    nb= (int)(Math.random()*10);
    System.out.print(nb);
    System.out.print("Guess the number between 0 and 9:");
    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("Try another Number");
        x=inp.nextInt();
        }
        else{
            System.out.print("you exceeded your allowed trials");
            break;

        }
        count++;

    }

    System.out.println("Found!!");
    System.out.println("Number of Guesses:" +count);


    inp.close();

   }
}
    while(x!= nb) {
        if(x>nb) System.out.println("Lesser");
        else if (x<nb) System.out.println("Bigger");
        System.out.println("Try another Number");
        x=inp.nextInt();
        count++;
        if(count == 4) {
            if(x == nb) break; // Leave the while loop and print "Found" message
            System.out.println("You exceeded your allowed trials");
            return; // Skip the message after the while-loop.
        }
    }

You can use your count variable to validate the quantity of the wrong answers and then us System.exit(0) method to finish the application.

Example:

if (count == 4 && x != nb) {
 System.out.println("you exceeded your allowed trials");
 //Terminate the application
 System.exit(0);
}
Related