user3563945
user3563945

Reputation: 29

Need a loop to repeat 3 times for a special condition

I have this situation: The user must enter a number for 'x'. If the value is >=0, a new game is created with this coordinate. If the user enters a negative number a message will be displayed and he will have another chance, there will be three chances to enter a correct number otherwise there will be no game. I tried an 'if-statement' for this case but it did not work well. Is there a way of doing that inside a loop?

Upvotes: 1

Views: 2565

Answers (3)

Salman
Salman

Reputation: 1264

        import java.util.Scanner;

    boolean isValidInput=false;
    int counter=0;

    Scanner sc = new Scanner(System.in);
    int userInput;

    while(counter<3 && isValidInput==false)
    {
        System.out.println("Enter a value: ");
           userInput = sc.nextInt();

        if(userInput>=0)
            isValidInput=true;

        else
            System.out.println("Please Enter valid input");

        counter++;

    }

Upvotes: 0

yitzih
yitzih

Reputation: 3118

final static int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;

while (!correctNumber)
{

    //get user input

    if (inputIsCorrect)
    {
        createANewGame();
        correctNumber = true;
    }
    else
    {
        System.out.println("Incorrect answer");
        attemptNumber++;
    }

    if(!inputIsCorrect && attemptNumber == NUMBER_OF_TRIES)
    {
        System.out.println("You have reached the max number of tries");
        System.exit(0);  //or whatever you want to happen
    }

 }

Upvotes: 3

DonyorM
DonyorM

Reputation: 1800

You can use a for loop with the following code

for(int x = 0; x < 3; x++) {
    //Perform logic
}

This will run exactly three times. You can change the 3 to make it run more or less times.

Upvotes: 0

Related Questions