在 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()
来刷新"Scanner
的内容:
You need to 'flush' the Scanner
contents with nextLine()
:
catch (Exception exc) {
input.nextLine();
System.out.println("invalid number");
}
<小时>
注意事项:
- 您可以删除
counter
变量,因为您没有使用它.否则,您可以将counter += 1
替换为counter++
. - 您可以将
while (!(numbers.size() == 3))
替换为while (numbers.size() != 3)
,甚至更好:while (numbers.size() <3)
. - 在捕获异常时,您应该尽可能具体,除非您有充分的理由不这样做.在您的情况下,
Exception
应替换为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屋!