Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
由于错误未处理,在Java中获取无限循环。我怎样才能解决这个问题?_Java_Error Handling_Infinite Loop - Fatal编程技术网

由于错误未处理,在Java中获取无限循环。我怎样才能解决这个问题?

由于错误未处理,在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

这是我的循环。如果输入了非整数,它将无休止地重复。从我所看到的情况来看,在循环的下一次运行中似乎没有清除异常。或者因为它接受以前的输入并将其分配给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();
  }

}

不要在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检查的异常捕获程序吗?