我是Java新手,想问你一个问题。
我写了以下代码,其中" numOfThreads
"应由用户通过控制台分配有效的int值。
但是,我希望得到一个结果,如果输入不正确并且我们进入catch块,则应该再次提示用户输入" numOfThreads
"直到它的类型和范围正确。
出于某种原因,我似乎进入了无限循环。你能帮忙吗?谢谢:))
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int numOfThreads;
boolean promptUser = true;
Scanner keyboard = new Scanner(System.in);
while (promptUser)
{
try{
numOfThreads = keyboard.nextInt();
promptUser = false;
}
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT
}
}
}
}
答案 0 :(得分:3)
它不是因为nextInt
尝试使用最后一个令牌。当输入无效时,它无法使用它。因此,以下nextInt
调用也无法使用它。在keyboard.nextLine
之前写一个numOfThreads = keyboard.nextInt();
,你没事。
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
// this consumes the invalid token now
keyboard.nextLine();
numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
// I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}