如何循环用户输入直到输入整数?

Sha*_*ail 4 java exception-handling input

我是Java的新手,我想继续询问用户输入,直到用户输入一个整数,这样就没有InputMismatchException了.我已经尝试过这段代码,但是当我输入一个非整数值时,我仍然会遇到异常.

int getInt(String prompt){
        System.out.print(prompt);
        Scanner sc = new Scanner(System.in);
        while(!sc.hasNextInt()){
            System.out.println("Enter a whole number.");
            sc.nextInt();
        }
        return sc.nextInt();
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间!

Jun*_*san 10

使用输入next代替nextInt.使用try catch来解析使用parseInt方法的输入.如果解析成功则中断while循环,否则继续.试试这个:

        System.out.print("input");
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Enter a whole number.");
            String input = sc.next();
            int intInputValue = 0;
            try {
                intInputValue = Integer.parseInt(input);
                System.out.println("Correct input, exit");
                break;
            } catch (NumberFormatException ne) {
                System.out.println("Input is not a number, continue");
            }
        }
Run Code Online (Sandbox Code Playgroud)


box*_*ish 6

更短的解决方案.只需在sc.next()中输入

 public int getInt(String prompt) {
    Scanner sc = new Scanner(System.in);
    System.out.print(prompt);
    while (!sc.hasNextInt()) {
        System.out.println("Enter a whole number");
        sc.next();
    }
    return sc.nextInt();

}
Run Code Online (Sandbox Code Playgroud)


Sha*_*ail 5

在处理 Juned 的代码时,我能够缩短它。

int getInt(String prompt) {
    System.out.print(prompt);
    while(true){
        try {
            return Integer.parseInt(new Scanner(System.in).next());
        } catch(NumberFormatException ne) {
            System.out.print("That's not a whole number.\n"+prompt);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)