Exception handling with a do-while loop in Java

后端 未结 5 713
孤街浪徒
孤街浪徒 2021-01-23 12:43

The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is e

5条回答
  •  情书的邮戳
    2021-01-23 13:30

    That is because when the next int is read using nextInt() and it fails, the Scanner still contains the typed contents. Then, when re-entering the do-while loop, input.nextInt() tries to parse it again with the same contents.

    You need to 'flush' the Scanner contents with nextLine():

    catch (Exception exc) {
        input.nextLine();
        System.out.println("invalid number");
    }
    

    Notes:

    • You can remove the counter variable, because you're not using it. Otherwise, you could replace counter += 1 by counter++.
    • You can replace while (!(numbers.size() == 3)) with while (numbers.size() != 3), or even better: while (numbers.size() < 3).
    • When catching exceptions, you should be as specific as possible, unless you have a very good reason to do otherwise. Exception should be replaced by InputMismatchException in your case.

提交回复
热议问题