Java Try-catch块,Catch块不会重新提示用户输入新值

时间:2016-09-14 12:45:00

标签: java try-catch

我是Java新手,想问你一个问题。

我写了以下代码,其中" numOfThreads"应由用户通过控制台分配有效的int值。

但是,我希望得到一个结果,如果输入不正确并且我们进入catch块,则应该再次提示用户输入" numOfThreads"直到它的类型和范围正确。

出于某种原因,我似乎进入了无限循环。你能帮忙吗?谢谢:))

import java.util.Scanner;

public class Main {

    public static void main(String args[]){

        int numOfThreads;
        boolean promptUser = true;

        Scanner keyboard = new Scanner(System.in);

        while (promptUser)
        {
            try{
                numOfThreads = keyboard.nextInt();
                promptUser = false;
            }
            catch(Exception e){
                System.out.println("Entry is not correct and the following exception is returned: " + e);
                numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

它不是因为nextInt尝试使用最后一个令牌。当输入无效时,它无法使用它。因此,以下nextInt调用也无法使用它。在keyboard.nextLine之前写一个numOfThreads = keyboard.nextInt();,你没事。

catch(Exception e){
    System.out.println("Entry is not correct and the following exception is returned: " + e);
    // this consumes the invalid token now
    keyboard.nextLine();
    numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
    // I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}