Skip to content
Advertisement

How can I remove this java exception error in my code?

When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn’t input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?

MY CODE

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int decimal = input.nextInt();
        if (decimal > 0 && decimal <= 100) {
            //code 
        }
        else {
            System.exit(0);
        }

When I input a string this message gets displayed. However, I just wanted to tell the user they exerted the wrong value and I wanted the program to quit.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at MainHandler.main(MainHandler.java:22)

I did try use hasNextInt at one point to try get rid of the exception error but I get an error when I use hasNextInt. https://imgur.com/a/OK8r3RH

Advertisement

Answer

Try with something like this. You surround your input inside a try-catch and as long as you get an Exception, you ask the user to put a number again. As soon as the input is valid (a number) you can proceed with your code:

    boolean canProceed = false;
    int number = -1;
    
    while (!canProceed) {
        try {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a number: ");
            number = Integer.parseInt(input.nextLine());
            canProceed = true;
        } catch (Exception e) {
            System.out.println("Invalid input.");
        }
    }
    
    if (number > 0 && number <= 100) {
        System.out.println("That's fine");
    }
    else {
        System.exit(0);
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement