算法应将3个整数存入ArrayList中。如果输入不是整数,那么应该有一个提示。当我执行我的代码时,执行catch
子句,但程序运行到无限循环。有人能引导我走向正确的方向,我很感激帮助。 :-D使用Java中的do-while循环进行异常处理
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));
}
}