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

时间:2015-11-24 07:40:57

标签: java loops input

我希望代码能够停止并再次等待输入,但它会像每次用户只需按Enter键一样运行,从而创建一个无限循环。

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

为什么会这样做?

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

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

3 个答案:

答案 0 :(得分:0)

您没有更改asking循环内while的值,因此它将是一个无限循环。

答案 1 :(得分:0)

试试这个。 nextInt没有阻止。 nextLine确实。

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

答案 2 :(得分:0)

我认为这会奏效:

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