Java:如何验证用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38850545/
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-11-03 03:49:40  来源:igfitidea点击:

Java: How to Validate User Input?

javavalidationjava.util.scanner

提问by Infernox CJC

I'm new to Java (actually only on my third day) but enjoy pushing myself when it comes to learning a new bit of code, I did the same when learning MATLAB as part of my Degree. In essence I like going one step further than what each particular lesson is trying to teach.

我是 Java 的新手(实际上只是在我的第三天),但在学习一些新代码时喜欢推动自己,我在学习 MATLAB 作为我学位的一部分时也是这样做的。从本质上讲,我喜欢比每节课试图教的更进一步。

I am currently writing a basic Calculator that can add, subtract, multiply and divide two numbers and have that core element working correctly. My "one step further" in this case was to make the program repeating with the option to exit via user input and to prevent any errors due to invalid user inputs.

我目前正在编写一个基本的计算器,它可以对两个数字进行加、减、乘和除,并使核心元素正常工作。在这种情况下,我的“更进一步”是使程序重复,并选择通过用户输入退出并防止由于无效用户输入而导致的任何错误。

I have been able to complete the repeating and exiting sections of this little project but have been unable to prevent errors caused by invalid user inputs, namely those caused by a String being inputted instead of the desired Int or Double. My goal is to prevent the error and instead ask for a valid input.

我已经能够完成这个小项目的重复和退出部分,但无法防止由无效用户输入引起的错误,即由输入字符串而不是所需的 Int 或 Double 引起的错误。我的目标是防止出现错误,而是要求提供有效的输入。

From what I have gathered, my problem can be addressed through the use of a Try/Catch Statement but I have no idea how to implement such a statement correctly. My best attempts, following similar-ish examples online have been met with failure, which I think is simply down to the way I have coded the program itself. As I said, I am new and have used lots of While Loops to achieve the desired behaviour and this is probably a horribly inefficient way of doing things.

从我收集到的信息来看,我的问题可以通过使用 Try/Catch 语句来解决,但我不知道如何正确实现这样的语句。我最好的尝试,在网上遵循类似的例子都失败了,我认为这只是我对程序本身进行编码的方式。正如我所说,我是新手并且使用了很多 While 循环来实现所需的行为,这可能是一种非常低效的做事方式。

Hopefully someone is able to point me in the right direction,
Conor

希望有人能够指出我正确的方向,
康纳

My best attempt thus far:

迄今为止我最好的尝试:

int InputValue;
InputValue = 1;
while (InputValue == 1)
{
    try
    {
        System.out.print ("Enter First Number: ");
        First = Input.nextDouble ();
        InputValue = 0;
    }
    catch (NumberFormatException e)
    {
        System.out.println ("Invalid Input");
        System.out.println (" ");
        System.out.print ("Enter First Number: ");
        First = Input.nextDouble ();
    }
}

But as stated above, this seems to make "First" invisible to the remainder of my code with the error:
"The local variable First may not have been initialized"

但如上所述,这似乎使“First”对我的代码的其余部分不可见,并出现错误:
“局部变量 First 可能尚未初始化”

Also tried:

还试过:

int InputValueX;
InputValueX = 1;
do
{
    System.out.println (" ");
    System.out.print ("Enter First Number: ");
    while (!Input.hasNextDouble ())
    {
        System.out.println ("Invalid Input");
        Input.next ();
    }
    First = Input.nextDouble ();
    InputValueX = 0;
}
while (InputValueX == 1);

This allows the code to run but does not address the invalid input error.

这允许代码运行,但不能解决无效输入错误。

And I don't think I can use a Boolean as that is what is looping my entire program (or can you use multiple Boolean? I tried that and got errors)

而且我不认为我可以使用布尔值,因为那是循环我整个程序的原因(或者您可以使用多个布尔值吗?我试过了,但出现错误)

http://pastebin.com/TTuCNQbx
- My Program, just over 100 lines long
- Area of interest between ~ 45 and 85

http://pastebin.com/TTuCNQbx
- 我的程序,只有 100 多行
- 感兴趣的区域介于 ~ 45 和 85 之间

回答by thorwinn

boolean firstNumber = false;
while (!firstNumber) {
    try {
        First = Input.nextDouble ();
        firstNumber = true;
    } catch (InputMismatchException e) {
        firstNumber = false;
        Input.nextLine();
    }
}

This should loop until a a proper Input was entered. I would recommend adding some System.out output to let the user know, that his input was invalid, and how a propper input might look like.

这应该循环直到输入正确的输入。我建议添加一些 System.out 输出,让用户知道他的输入无效,以及正确的输入可能是什么样子。

回答by xenteros

Actually every user inputs Strings. Then You have to validate the Stringif it's acceptable format for you or not.

实际上每个用户都输入了Strings。然后您必须验证它String是否适合您的格式。

Let's assume you already have user's input stored in String input:

假设您已经将用户的输入存储在String input

String input;
//some code for getting the input
try {
    double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
    e.printStackTrace();
}

This is the general construction for parsing Stringinto double. Now you can wrap it into a loop which would scan the input until you would find what you wanted. Feel free to use flags e.g.

这是解析Stringdouble. 现在您可以将其包装成一个循环,该循环将扫描输入,直到找到您想要的内容。随意使用标志,例如

boolean found = false;
try {
    double dbl = Double.parseDouble(input);
    found = true; //this line won't be executed if parsing fails
} catch (NumberFormatException e) {
    e.printStackTrace();
    found = false;
}

回答by BSM

Surround the lines like Input.next* in your code with try/catch block. Catch the RuntimeException or in particularly InputMismatchException (best practice) like below,

使用 try/catch 块将代码中的 Input.next* 之类的行括起来。捕获 RuntimeException 或特别是 InputMismatchException(最佳实践),如下所示,

    boolean Run = true;
    while (Run)
    {
        Scanner input = new Scanner (System.in);
        int i = 0;
        try
        {
            i = input.nextInt();
        }
        catch(InputMismatchException ime)
        {
            System.out.println("message to enter the input in valid format");
        }
    }