Vit*_*nko 1 java loops infinite-loop while-loop
这里有一个while循环我有这个问题:
while((input = InputHandler.getInt()) != 1 && input != 2){
if(input == InputHandler.CODE_ERROR)
System.out.print("Input must be a number");
}
Run Code Online (Sandbox Code Playgroud)
这个while循环只接受一次输入而不再请求它,所以它循环使用整个时间输入的输入.我在这里做错了什么,因为对我来说这个wile循环工作真的很奇怪?
InputHandler类:
public class InputHandler {
public static Scanner in = new Scanner(System.in);
public static int CODE_ERROR = -6;
public static int getInt(){
try{
return in.nextInt();
} catch(InputMismatchException e){
return CODE_ERROR;
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前,如果在命令行输入非整数,则代码将进入无限循环.这是因为您的in.nextInt()方法抛出异常并在扫描程序中留下了有问题的值.
您需要通过调用in.next();以下内容来使用导致异常的无效令牌:
public static void main(String[] args) throws Exception {
int input;
while ((input = InputHandler.getInt()) != 1 && input != 2) {
if (input == InputHandler.CODE_ERROR)
System.out.print("Input must be a number");
}
}
public static class InputHandler {
public static Scanner in = new Scanner(System.in);
public static int CODE_ERROR = -6;
public static int getInt(){
try{
return in.nextInt();
} catch(InputMismatchException e){
in.next(); // <------------------ this should solve it
return CODE_ERROR;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
990 次 |
| 最近记录: |