Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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_Loops_Input - Fatal编程技术网

Java 为什么这段代码不等待输入

Java 为什么这段代码不等待输入,java,loops,input,Java,Loops,Input,我希望代码停止并再次等待输入,但它的运行就像用户每次按enter键一样,创建了一个无限循环 while(asking) { try { int answer = input.nextInt(); } catch(Exception InputMismatchException) { System.out.println("Please only enter numbers."); } } 为什么会这样 编辑:我不担心

我希望代码停止并再次等待输入,但它的运行就像用户每次按enter键一样,创建了一个无限循环

while(asking) {
    try {   
        int answer = input.nextInt();   
    }
    catch(Exception InputMismatchException) { 
        System.out.println("Please only enter numbers.");
    }
}
为什么会这样

编辑:我不担心退出while循环。问题是它不会等待输入


EDIT2:如果没有触发异常,它将按预期运行。(即用户输入了一个整数限制内的数字)

循环时,您不能更改
内的
询问
的值,因此它将是一个无限循环。

试试这个。nextInt没有阻塞。nextLine有

while(asking) {
    try {   
        int answer = input.nextInt();   
    }
    catch(Exception InputMismatchException) { 
        System.out.println("Please only enter numbers.");
    }
}
while(asking) {
    int answer;
    try {   
        answer = Integer.parseInt(input.nextLine());
    }
    catch(Exception NumberFormatException) { 
        System.out.println("Please only enter numbers.");
    }
}

我认为这会奏效:

while(asking) {
    try {   
        int answer = input.nextInt();   
    }
    catch(Exception InputMismatchException) { 
        System.out.println("Please only enter numbers.");
        input.next();
    }
}

您需要调用
nextLine
,以防收到执行选项。否则它会创建一个无限循环。哪个值有询问,它什么时候会改变?你在哪里设置
询问
?@EduardoYáñezParareda无所谓,将其设置为true,永远不要改变它问题会重现。