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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19130217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:21:31  来源:igfitidea点击:

How to loop user input until an integer is inputted?

javainputexception-handling

提问by Shail

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.

我是 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();
}

Thanks for your time!

谢谢你的时间!

采纳答案by Shail

Working on Juned's code, I was able to make it shorter.

在处理 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);
        }
    }
}

回答by Juned Ahsan

Take the input using nextinstead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue. Try this:

使用next代替 来获取输入nextInt。使用 parseInt 方法放置一个 try catch 来解析输入。如果解析成功,则中断 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");
            }
        }

回答by Niki

As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.

作为替代方案,如果它只是一个单数整数 [0-9],那么您可以检查其 ASCII 代码。它应该是介于 48-57 之间的整数。

Building up on Juned's code, you can replace try block with an if condition:

以 Juned 的代码为基础,您可以用 if 条件替换 try 块:

    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;
            if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
                System.out.println("Correct input, exit");
                    break;
            }
            System.out.println("Input is not a number, continue");
    }

回答by boxfish

Shorter solution. Just take input in sc.next()

更短的解决方案。只需在 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();

}