2

我正在为一个需要我们将输入字符串传递给 Integer.parseInt 函数的类程序工作。在我交出字符串之前,我想确保它不包含任何非数字值。我用 Pattern.matches 创建了这个 while 函数来尝试这个。这是代码:

while((Pattern.matches("[^0-9]+",inputGuess))||(inputGuess.equals(""))) //Filter non-numeric values and empty strings.
                {
                    JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
                    inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
                }

每当我输入任何字母、标点符号或“特殊字符”时,while 语句都会生效。但是,每当我介绍字母、标点符号或“特殊字符”和数字的任何组合时,程序就会崩溃并烧毁。我的问题是:有没有办法将 Pattern.matches 与正则表达式一起使用,这将允许我防止将数字和字母、标点符号或“特殊字符”的任何组合传递给 Integer.parseInt,但仍然只允许数字交给 Integer.parseInt。

4

2 回答 2

1

尝试这个:

!Pattern.matches("[0-9]+",inputGuess)

或者更简洁地说:

!Pattern.matches("\\d+",inputGuess)

使用+也避免了检查空字符串的需要。

请注意,仍然有可能因Integer.parseInt越界而失败。

为了防止这种情况,你可以这样做

!Pattern.matches("\\d{1,9}",inputGuess)

尽管这排除了一些大的有效整数值(任何十亿或更多)。

老实说,我只会使用 try-catchInteger.parseInt并在必要时检查它的符号。

于 2013-11-03T01:07:36.567 回答
0

您的程序不起作用,因为Pattern.matches需要整个字符串来匹配模式。相反,即使字符串的单个子字符串与您的模式匹配,您也希望显示错误。

这可以通过Matcher类来完成

public static void main(String[] args) {
    Pattern p = Pattern.compile("[^\\d]");

    String inputGuess = JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12.");

    while(inputGuess.equals("") || p.matcher(inputGuess).find()) //Filter non-numeric values and empty strings.
    {
        JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
        inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
    }
}
于 2013-11-03T01:22:50.620 回答