[英]Getting an infinite loop in Java due to error miss-handling. How can I fix this?
這是我的循環。 如果輸入非整數,它將無休止地重復。 從我看到的情況來看,似乎在下一輪循環中未清除異常。 或者因為它采用了先前的輸入並將其分配給menuChoice。 我怎樣才能解決這個問題?
while(!console.hasNextInt())
{
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
}
}
不要在while循環中檢查int,請檢查任何輸入令牌:
while(console.hasNext()){
if(console.hasNextInt()){
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
}
}else{
//throw away non-ints
console.next();
}
}
這可能會更快,因為hasNextInt()
和nextInt()
都嘗試將下一個標記解析為int。 在此解決方案中,解析僅執行一次:
while(console.hasNext()){
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
} finally {
//throw away non-ints
console.next();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.