简体   繁体   中英

try-catch that will catch if user input is incorrect

I am wondering how to do it in a way so that the user can both opt out of entering integers, and so that if the user does not enter an integer, it will catch it and re-prompt them without ending the program. I need the scanner to take in both int and string types. Is there a way to do this? Or a way around it?

/* The following method asks a user to input a series of integers. 
 * The user can stop at any time buy entering "quit"
*/

public static void readSeries()
{ 
    int integer;
    Scanner scan = new Scanner(System.in);

    System.out.println("Please enter a series of integers. If you wish to stop, enter 'quit'. ");
    System.out.println();

try{
    while(true) 
    {
        System.out.println("Enter an integer: "); // asks user to enter an integer
        integer = scan.nextInt();

        if(scan.equals (0)){break;}             // allows user to stop entering numbers 
    }       

    } catch(NumberFormatException nfe){System.out.println("Invalid Entry!");}

}
}

Start by breaking you're requirements down.

First, you need to be able to read both text and int values from the user. You need to be able to do this because you need to check for the "exit" condition. So, instead of using Scanner#nextInt , you should probably be using Scanner#nextLine instead.

String input = scan.nextLine();

Next, you need to check the input from the user to see if it's meets the "exit" condition or not. If it doesn't, you need to try and convert the input to an int value and process any conversion issues which might occur

Integer value = null;
//...
if (escape.equalsIgnoreCase(input)) {
    exit = true;
} else {
    try {
        value = Integer.parseInt(input);
    } catch (NumberFormatException exp) {
        System.out.println("!! " + input + " is not a valid int value");
    }
}

Okay, once you have this working okay, you need to wrap it in side of a loop, now, because we HAVE to loop at least once, a do-while would be suitable (checking the exit condition of the loop at the end of the loop instead of the start)

Integer value = null;
boolean exit = false;

do {
    System.out.print(prompt);
    String input = scanner.nextLine();

    if (escape.equalsIgnoreCase(input)) {
        exit = true;
    } else {
        try {
            value = Integer.parseInt(input);
        } catch (NumberFormatException exp) {
            System.out.println("!! " + input + " is not a valid int value");
        }
    }
} while (value == null && !exit);

So, when the loop exists, either value will be a valid integer or null . You might be thinking why this is important. null lets us know that their are no more valid values from the user, otherwise you would need to have come up with a int exit value, but what happens if the user chooses to use that value as their input?

Okay, now, we need to ask the user to do this a lot of times, so, this calls for a method!

public Integer promptForInt(String prompt, Scanner scanner, String escape) {
    Integer value = null;
    boolean exit = false;

    do {
        System.out.print(prompt);
        String input = scanner.nextLine();

        if (escape.equalsIgnoreCase(input)) {
            exit = true;
        } else {
            try {
                value = Integer.parseInt(input);
            } catch (NumberFormatException exp) {
                System.out.println("!! " + input + " is not a valid int value");
            }
        }
    } while (value == null && !exit);

    return value;
}

Now, you can simply use another loop to call the method as many times as you need to

List<Integer> values = new ArrayList<>(25);
Integer value = null;
do {
    value = promptForInt("Please enter a series of integers. If you wish to stop, enter 'quit'. ", new Scanner(System.in), "quit");
    if (value != null) {
        values.add(value);
    }
} while (value != null);

System.out.println("You have input " + values.size() + " valid integers");

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