我正在为一个需要我们将输入字符串传递给 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。