Exception handling with a do-while loop in Java

2020-04-30 06:52发布

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 executed, but the program runs into a infinite loop. Could someone guide me into the right direction, I appreciate the help. :-D

package chapter_08;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class IntegerList {
    static List<Integer> numbers = new ArrayList<Integer>();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter = 1;
        int inputNum;

        do {
            System.out.print("Type " + counter + " integer: " );
            try {
                inputNum = input.nextInt();
                numbers.add(inputNum);
                counter += 1;
            }
            catch (Exception exc) {
                System.out.println("invalid number");
            }
        } while (!(numbers.size() == 3));
    }
}

5条回答
何必那么认真
2楼-- · 2020-04-30 07:30

If inputNum = input.nextInt(); cannot be fit into an int and a InputMismatchException is raised, the input of the Scanner is not consumed.

So after the catch, it loops and it goes again here :

inputNum = input.nextInt();

with exactly the same content in the input.

So you should execute input.nextLine(); in the catch statement to discard the current input and allow a new input from the user.
Besides it makes more sense to catch InputMismatchException rather than Exception as other exception with no relation with a mismatch could occur and it would not be useful to display to the user "invalid number " if it is not the issue :

    catch (InputMismatchException e){
        System.out.println("invalid number ");
        input.nextLine();
    }
查看更多
Animai°情兽
3楼-- · 2020-04-30 07:32

You need to move the scanner to the next line. Add this line of code below the error message in the catch section.

input.nextLine();
查看更多
唯我独甜
4楼-- · 2020-04-30 07:47

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.
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-04-30 07:55

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.

查看更多
小情绪 Triste *
6楼-- · 2020-04-30 07:55

try changing

inputNum = input.nextInt();

to

String inputText=input.next();
inputNum = Integer.valueOf(inputText);

it works perfectly well.

查看更多
登录 后发表回答