do while loop and user input issue

Shumsky :

I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int number = 0;


    do {
        System.out.println("Input a number!");
        number = scanner.nextInt();
        if (!scanner.hasNextInt()) {
            System.err.println("This is not a number");
        }

    } while (!scanner.hasNextInt());

    System.out.println("You entered: " + number);

}
Sankeeth Ganeswaran :

You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String input = "";
    int number = 0;
    boolean end = true;


    do {
        System.out.println("Input a number!");
        input = scanner.nextLine();
        try {
            number = Integer.parseInt(input);
            end = true;
        } catch(Exception e) {
            System.err.println("This is not a number");
            end = false;
        } 

    } while (!end);

    System.out.println("You entered: " + number);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361156&siteId=1