Inputting a string into my code that an int is required and I get a java error how can I fix this?

Tags:



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?

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

Answer

The nextInt method throws an exception if the input is not an integer. If you want to prevent this, just use the method hasNextInt to check before read it.



Source: stackoverflow