我尝试过执行do while循环并得到一个无限循环,而不是在catch部分重复错误消息。在用户输入数值之前,如何使此代码循环播放?
try {
System.out.print("How many people are in your group? ");
int group = sc.nextInt();
System.out.println("Okey, " + group + " people");
}
catch (InputMismatchException e) {
System.out.println("Error, please enter a numerical value");
}
答案 0 :(得分:0)
只需将while(true)
循环添加到您的代码中即可:
public static int getInt(Scanner sc) {
while(true) {
try {
System.out.print("How many people are in your group? ");
int group = sc.nextInt();
System.out.println("Okey, " + group + " people");
return group;
} catch (InputMismatchException e) {
System.out.println("Error, please enter a numerical value");
}
}
}
答案 1 :(得分:0)
由于do
实例(while
)的内部缓冲区使您保持错误,所以您的代码(用Scanner
... sc
语句包围)将陷入无限循环。 )在发生InputMismatchException
时输入。
您可以使用Scanner.next
方法(无论其值是什么,都读取String
)和Integer.parseInt
进行转换来重写逻辑:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer group = null;
do {
try {
System.out.print("How many people are in your group? ");
String input = sc.next();
group = Integer.parseInt(input);
System.out.println("Okey, " + group + " people");
} catch (NumberFormatException e) {
System.out.println("Error, please enter a numerical value");
}
} while(group == null);
}