0

I have the following code, where I need the user to input an int > 0.

    int rows = 0;
    while(rows <= 0){
        System.out.println("How many rows are in the matrix?");
        try{
            rows = scan.nextInt();
            if (rows <= 0){
                System.out.println("Invalid input, try again");
                //scan.nextLine(); // !A!
            }
        } catch(InputMismatchException e){
            System.out.println("Invalid input, try again");
            //scan.nextLine(); // !B!
        } 
    }

Why does it work without uncommenting A, but does not work without uncommenting B? In other words, why does the catch block need scan.nextLine(), but the try block does not?

Aren't both of them printing a new line after? Why does the catch block have this requirement?

  • 2
    If `nextInt()` fails, you need to move past the invalid token. If `nextInt()` succeeds, it moves to the next token automatically. – khelwood Dec 13 '21 at 17:46
  • Oh, so because nextInt() was an int in the try block, it will not need to move past because it was valid (even though it was invalid by my subjective needs for the program). Thank you – Carter Karl Falkenberg Dec 13 '21 at 17:47

0 Answers0