仅使用计数器对数字范围和数字值进行 JAVA 输入验证

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

JAVA Input Validation for Number Range and Numeric values only with counter

javavalidationcounter

提问by user3537993

I am trying to complete a task and I am unsure what route to take. I have tried while, if, and a combination of statements and cannot get the input validation I need.

我正在尝试完成一项任务,但我不确定该走哪条路。我已经尝试了while, if, 和语句的组合,但无法获得我需要的输入验证。

  • I am trying to validate user input and ensure their input is a number between 0 and 10 (excluding 0 and 10).
  • Also I need to make sure that what they do enter is a number and not some symbol or letter.
  • Finally I need a counter that will allow them 3 chances to input the correct information.
  • 我正在尝试验证用户输入并确保他们的输入是 0 到 10 之间的数字(不包括 0 和 10)。
  • 此外,我需要确保他们输入的是数字而不是某些符号或字母。
  • 最后,我需要一个计数器,让他们有 3 次机会输入正确的信息。

The code below is my method I am trying to setup to accomplish this.

下面的代码是我尝试设置以完成此操作的方法。

private static int getNumericInput(String quantity) {
    int count = 0;
    String input;
    input = JOptionPane.showInputDialog(quantity);
    int range = Integer.parseInt(input);

    while ((range > 9 || range < 1) && (count < 2)) {
        JOptionPane.showMessageDialog(null, 
                "Sorry that input is not valid, please choose a quantity from 1-9");
        input = JOptionPane.showInputDialog(quantity);
        count++;
    }
    if (count == 2) {
        JOptionPane.showMessageDialog(null, 
                "Sorry you failed to input a valid response, terminating.");
        System.exit(0);
    }
    return range;
}

采纳答案by ug_

As others have said to see if a Stringis a valid integer you catch a NumberFormatException.

正如其他人所说,要查看 aString是否为有效整数,您可以捕获 a NumberFormatException

try {
    int number = Integer.parseInt(input);
    // no exception thrown, that means its a valid Integer
} catch(NumberFormatException e) {
    // invalid Integer
}

However I would also like to point out a code change, this is a prefect example of a do while loop. Do while loops are great when you want to use a loop but run the condition at the end of the first iteration.

但是,我还想指出代码更改,这是 do while 循环的完美示例。当您想使用循环但在第一次迭代结束时运行条件时,Do while 循环非常有用。

In your case you always want to take the user input. By evaluating the while loops condition after the first loop you can reduce some of that duplicate code you have to do prior to the loop. Consider the following code change.

在您的情况下,您总是希望接受用户输入。通过在第一个循环之后评估 while 循环条件,您可以减少在循环之前必须执行的一些重复代码。考虑以下代码更改。

int count = 0;
String input;
int range;
do {
    input = JOptionPane.showInputDialog(quantity);
    try {
        range = Integer.parseInt(input);
    } catch(NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Sorry that input is not valid, please choose a quantity from 1-9");
        count++;
        // set the range outside the range so we go through the loop again.
        range = -1;
    }
} while((range > 9 || range < 1) && (count < 2));

if (count == 2) {
    JOptionPane.showMessageDialog(null, 
            "Sorry you failed to input a valid response, terminating.");
    System.exit(0);
}
return range;

回答by Zoyd

This line:

这一行:

int range = Integer.parseInt(input);

appears before your while loop. So, you know how to convert the input to an int. The next step is to realize that you should do it each time the user gives you an input. You are almost there.

出现在你的 while 循环之前。因此,您知道如何将输入转换为 int。下一步是意识到每次用户给你输入时你都应该这样做。你快到了。

回答by Asif Bhutto

If input string does not contain a valid number format in string then this line will throw NumberFormatException

如果输入字符串在字符串中不包含有效的数字格式,则此行将抛出 NumberFormatException

int range = Integer.parseInt(input)

You need to put it try catch block

你需要把它 try catch 块

try {
            Integer.parseInt("test");
        } catch (java.lang.NumberFormatException e) {
                count++; //allow user for next attempt.
              //    showInputDialog HERE
              if(count==3) {
                // show your msg here in JDIalog.
              System.exit(0);
           }
}

For 3 chances to input the correct information, you need to use loop, inside loop call your showInputDialog method

对于输入正确信息的 3 次机会,您需要使用循环,在循环内调用您的 showInputDialog 方法

回答by Praz

As of JDK 1.8, you can use the temporalpackage to solve this, along-with the try-catch as shown by rest of the answers from this thread:

从 JDK 1.8 开始,您可以使用temporal包来解决这个问题,同时使用 try-catch,如该线程的其余答案所示:

import java.time.temporal.ValueRange;
...
public static void main (String[] args){
ValueRange range = ValueRange.of(1,9);

    int num, counter = 0;

    do {
    System.out.print("Enter num: ");
    num = Integer.parseInt(scanner.next());
    if (range.isValidIntValue(num))
        System.out.println("InRange");
    else 
        System.out.println("OutOfRange");

    counter ++;
    } while (!range.isValidIntValue(num) && counter < 3);
...
}