由于错误未处理,在Java中获取无限循环。我怎样才能解决这个问题?
这是我的循环。如果输入了非整数,它将无休止地重复。从我所看到的情况来看,在循环的下一次运行中似乎没有清除异常。或者因为它接受以前的输入并将其分配给menuChoice。我怎样才能解决这个问题由于错误未处理,在Java中获取无限循环。我怎样才能解决这个问题?,java,error-handling,infinite-loop,Java,Error Handling,Infinite Loop,这是我的循环。如果输入了非整数,它将无休止地重复。从我所看到的情况来看,在循环的下一次运行中似乎没有清除异常。或者因为它接受以前的输入并将其分配给menuChoice。我怎样才能解决这个问题 while(!console.hasNextInt()) { try { menuChoice = console.nextInt(); } catch(InputMismatchException e) { System.out.println("The s
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();
}
}
不要在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();
}
}
这可能会更快,因为
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();
}
}
我们需要更多的代码-我假设
console
是一个扫描器,它是如何创建/配置的?我们需要更多的代码-我假设console
是一个扫描器,它是如何创建/配置的?理论上,我还需要带有int检查的异常捕捉器吗?理论上,我还需要带有int检查的异常捕获程序吗?