使用Java中的do-while循环进行异常处理 [英] Exception handling with a do-while loop in Java
问题描述
算法应该将3个整数带入ArrayList。如果输入不是整数,那么应该有一个提示。当我执行我的代码时,执行 catch
子句,但程序运行到无限循环。有人可以引导我走向正确的方向,我很感激帮助。 :-D
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));
}
}
推荐答案
那是因为当使用 nextInt()
读取下一个int并且它失败时, Scanner
仍然包含键入的内容。然后,当重新进入do-while循环时, input.nextInt()
尝试使用相同的内容再次解析它。
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.
您需要使用 nextLine()
'
catch (Exception exc) {
input.nextLine();
System.out.println("invalid number");
}
注意:
- 你可以删除
计数器
变量,因为你是不使用它。否则,你可以用counter ++
替换counter + = 1
。 - 你可以替换
while(!(numbers.size()== 3))
withwhile(numbers.size()!= 3)
,甚至更好:while(numbers.size()< 3)
。 - 当捕获异常时,你应该尽可能具体,除非你有充分的理由不这样做。在您的情况下,
异常
应替换为InputMismatchException
。
- You can remove the
counter
variable, because you're not using it. Otherwise, you could replacecounter += 1
bycounter++
. - You can replace
while (!(numbers.size() == 3))
withwhile (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 byInputMismatchException
in your case.
这篇关于使用Java中的do-while循环进行异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!