1

When a letter is typed in, I got stuck in an endless loop from line "col = scanner.nextInt();" directly to the Exception-Message. How can I edit my code, so the user will be able to input another time after a wrong input?

int inputInt(String message, int min, int max) {
        System.out.println(message);
        boolean repeat = true;
        int col = 0;
        while(repeat) {
            try {
                col = scanner.nextInt();
                if(col>=min && col<=max) {
                    repeat = false;
                    break;
                }
                if(col<min || col>max) {
                    System.out.println("Input only from "+min+" to "+max+" possible");
                }
            }
            catch(InputMismatchException e) {
                System.out.println("Input only from "+min+" to "+max+" possible");
                //col = 0;
                //System.err.println("Exception caught: " + e.getMessage());
            }
        }

        return col;
    }
Chris F
  • 85
  • 4
  • The suggested duplicate is relevant, consider adding `scanner.nextLine()` in your `catch` block. – Arnaud Jun 13 '18 at 15:11
  • 2
    Works perfectly. Thank you very much! btw: with just the reference to the other question, I tried `scanner.nextLine()` only in the `try` block. Your comment helped a lot. – Chris F Jun 13 '18 at 15:19

0 Answers0