Rhendz
Rhendz

Reputation: 101

Try-Catch inside While Loop

The code below asks the user how many racers he/she would like.

while (true) { // loops forever until break
    try { // checks code for exceptions
        System.out.println("How many racers should" + " participate in the race?");
        amountRacers = in.nextInt();
        break; // if no exceptions breaks out of loop
    } 
    catch (InputMismatchException e) { // if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        continue; // continues to loop if exception is found
    }
}

If a number is entered at amoutnRacers = in.nextInt(); the code breaks out of the loop and the rest of the program runs fine; however, when I enter something such as "awredsf" it should catch that exception, which it does. Instead of prompting the user again it loops continuously, which to me does not make sense.

The program prints like this when looping continuously:

How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race?Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null ...

I do not understand what is going on amountRacers = in.nextInt(); so why is the user not able to enter a number?

Upvotes: 4

Views: 39229

Answers (4)

JulitOw
JulitOw

Reputation: 1

This works for me.

while (true) {
        try {
            System.out.print("Ingrese la cantidad de puestos de atención: ");
            int puestos = Integer.parseInt(scn.nextLine());
            break;
        }
        catch (NumberFormatException e) {
            System.out.println("Ingrese un valor correcto");
            scn.reset();
            continue;
        }
    }

Upvotes: 0

Remzi Cavdar
Remzi Cavdar

Reputation: 187

Why use a loop with a try and catch?

My advice would be to always use a try and catch with either a while or do while loop, so you can ask the user to repeat his/her input. It also depends which loop you already use and/or on how your code is structured.

For example if you already have a do while loop then I would advice you to simply adjust/modify your existing loop.

I will post some examples on how you can use a try and catch with a loop to repeat the input after a user has provided a wrong one.

See examples below:

Example 1

Scanner input = new Scanner(System.in);
int exampleInput = 0;
do {
    try {
        System.out.print("\nEnter an integer from 1 to 25: ");
        exampleInput = input.nextInt();
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer from 1 to 25");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (exampleInput < 1 || exampleInput > 25);
System.out.println("Print exampleInput: " + exampleInput);

Example 2

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDone = false;
do {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDone = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (!isDone);
System.out.println("Print exampleInput: " + exampleInput);

Example 3

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDoneLoop2 = false;
while (!isDoneLoop2) {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDoneLoop2 = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
}
System.out.println("Print exampleInput: " + exampleInput);

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

Just add input.next() once you catch InputMismatchException.

catch (InputMismatchException e) { //if an exception appears prints message below
    System.err.println("Please enter a number! " + e.getMessage());
    input.next(); // clear scanner wrong input
    continue; // continues to loop if exception is found
}

You need to clear the wrong input, which scanner automatically does not.

Upvotes: 16

ConsciousCoder
ConsciousCoder

Reputation: 13

You may need to create a Scanner class for getting standard input streamed from the keyboard. You should have a statement somewhere in your code that creates an instance of a Scanner class like: Scanner in = new Scanner(System.in); so the " in " variable in your statement: amountRacers = in.nextInt(); waits and scans for entered input from the keyboard and stores it.

Upvotes: 0

Related Questions