【问题标题】:JAVA Input Validation for Number Range and Numeric values only with counter数字范围和数值的 JAVA 输入验证仅使用计数器
【发布时间】:2014-04-24 19:03:34
【问题描述】:

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

  • 我正在尝试验证用户输入并确保他们的输入是介于 0 和 10 之间的数字(不包括 0 和 10)。
  • 我还需要确保他们输入的是数字而不是符号或字母。
  • 最后我需要一个计数器,让他们有 3 次机会输入正确的信息。

下面的代码是我正在尝试设置的方法。

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;
}

【问题讨论】:

  • 很好很诚实的问题:)

标签: java validation counter


【解决方案1】:

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

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

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

在您的情况下,您总是希望接受用户输入。通过在第一个循环之后评估 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;

【讨论】:

    【解决方案2】:

    这一行:

    int range = Integer.parseInt(input);
    

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

    【讨论】:

      【解决方案3】:

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

      int range = Integer.parseInt(input)
      

      你需要把它放在 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);
                 }
      }
      

      为了3次输入正确信息,你需要使用循环,在循环内部调用你的showInputDialog方法

      【讨论】:

        【解决方案4】:

        从 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);
        ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-13
          • 2012-11-27
          • 2015-09-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多