Exception handling with a do-while loop in Java

后端 未结 5 645
孤街浪徒
孤街浪徒 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:18

    You should to use a break; in your catch(){} like so :

    try {
        inputNum = input.nextInt();
        numbers.add(inputNum);
        counter += 1;
    } catch (Exception e) {
        System.out.println("invalid number ");
        break;
    }
    

    So if one input is not correct break your loop.

提交回复
热议问题