Scanner input = new Scanner( System.in );
System.out.println("Input the minimum necessary word count in a single article!");
int minArticleLength1 = input.nextInt();
while (minArticleLength1<0){
System.out.println("Input the minimum necessary word count in a single article!");
minArticleLength1 = input.nextInt();
}
正如您在程序的这一部分中看到的那样,您需要为int类型变量赋值。如果我输入int类型值,一切正常,但如果我指定一个像1.1这样的值,程序会启动一个无限循环,直到我停止它。我应该在代码中更改什么来保持程序不接受double值,即使int是必要的,这样如果我输入像1.1这样的双值,程序会要求再次输入值?
答案 0 :(得分:2)
您可以在循环中使用try...catch
语句来捕获无效输入。
while (minArticleLength1 < 0){
System.out.println("Input the minimum necessary word count in a single article!");
try {
minArticleLength1 = input.nextInt();
} catch (InputMismatchException imex) }
System.out.println("Please enter a valid integer.");
minArticleLength1.nextLine();
}
}