简体   繁体   中英

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?

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.

Today i solved this problem :-) This is my code. I think that i help

public int choice () throws Exception{
    Scanner read = new Scanner(System.in));
    System.out.println("Choose the option from the upper list");
    int auxiliaryChoiceMenu = 5;
    int auxiliaryVariable = -1;
    boolean auxiliaryBoolean = false;
    while (!auxiliaryBoolean) {
        try {
            auxiliaryVariable = read.nextInt();
            read.nextLine();
        } catch (Exception e) {
            System.out.println("incorrect data, try again"+e);
            read.nextLine();
            continue;
        }

        if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
            System.out.println("incorrect data, try again");
        } else {
            auxiliaryBoolean = true;
        }
        choiceMenu = auxiliaryVariable;

    }
        return choiceMenu;
        //choicemenu is a external variable
}

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.

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

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

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