仅使用计数器对数字范围和数字值进行JAVA输入验证 [英] JAVA Input Validation for Number Range and Numeric values only with counter

查看:242
本文介绍了仅使用计数器对数字范围和数字值进行JAVA输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成一项任务,我不确定要采取的路线。我已尝试如果,以及语句组合,无法获得我需要的输入验证。

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.


  • 我正在尝试验证用户输入并确保其输入是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;
}


推荐答案

正如其他人所说的那样如果 String 是一个有效的整数,你会得到一个 NumberFormatException

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

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

但是我还要指出代码更改,这是do while循环的完美示例。当你想要使用循环但是在第一次迭代结束时运行条件时,while循环是否很好。

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.

在你的情况下你总是想要用户输入。通过在第一个循环之后评估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.

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;

这篇关于仅使用计数器对数字范围和数字值进行JAVA输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆