字符串到整数输入验证转换

时间:2017-01-29 08:31:53

标签: java

我正在编写一个类来验证来自另一个类的输入。除了我的验证不能接受确切的高范围值之外,一切似乎都有效。我不知道它为什么不接受它 - 例如 - 如果highRange是10并且用户输入10,!(10> 10)。如果你们可以关心我的代码,我会很感激!

import javax.swing.JOptionPane;

public class InputVerification {
private String input;
private int lowRange;
private int highRange;
private int invalidNum;

public InputVerification(String input, int lowRange, int highRange, int invalidNum) {
    this.input = input;
    this.lowRange = lowRange;
    this.highRange = highRange;
    this.invalidNum = invalidNum;
}

public int intVerify() {

    String userInput = null;
    int intInput = 0;
    do {
        do {
            try {

                /**
                 * handles any text entered instead of numbers enter -2 if
                 * you don't need an invalid number
                 */

                userInput = JOptionPane.showInputDialog(this.input);

                intInput = Integer.parseInt(userInput);

                if ((intInput > highRange || intInput < lowRange) && !(userInput.matches("[a-zA-Z]+"))) {

                    JOptionPane.showMessageDialog(null,
                            "Error! Please pick a number between " + lowRange + "-" + highRange + ".");

                }

            } catch (NumberFormatException e) {

                    JOptionPane.showMessageDialog(null,
                            "Error! Please pick a number between " + lowRange + "-" + highRange + ".");

            }

        } while (!userInput.matches("^[0-9]"));

        if ((intInput > highRange || intInput < lowRange)) {

            /**
             * 
             * sends an error message if the number is higher than 100 or
             * lower than 1 as long as the input was not text
             * 
             */

            JOptionPane.showMessageDialog(null,
                    "Error! Please pick a number between " + lowRange + "-" + highRange + ".");

        }

        if (invalidNum != -2 && intInput == invalidNum) {
            JOptionPane.showMessageDialog(null, "Error! Please pick a number between " + lowRange + "-" + highRange
                    + " that is not " + invalidNum + ".");
        }

    } while ((intInput > highRange || intInput < lowRange || intInput == invalidNum)
            && !(userInput.matches("[a-zA-Z]+")));

    return intInput;

    }
}

3 个答案:

答案 0 :(得分:2)

\index

答案 1 :(得分:1)

while (!userInput.matches("^[0-9]"));

应该是

while (!userInput.matches("^[0-9]+"));

答案 2 :(得分:1)

if条件中存在错误,用于检查数字是否在范围内: if ((intInput > highRange || intInput < lowRange) && !(userInput.matches("[a-zA-Z]+"))) {

通过此检查,数字应超出范围不是有效数字。您应该将其更改为 OR ||,即 if ((intInput > highRange || intInput < lowRange) || !(userInput.matches("[a-zA-Z]+"))) {

请注意,检查输入是否与正则表达式匹配(如果它是一个数字)不会非常有用,因为在之前将其解析为整数时会出现异常。