我遇到的问题是这段代码:
String birthString = JOptionPane.showInputDialog(
null, "Enter birth year: ", "How long have you been alive?",
JOptionPane.QUESTION_MESSAGE);
Pattern p = Pattern.compile("[A-Z,a-a,&%$#@!()*^]");
Matcher m = p.matcher(birthString);
if (m.find()){
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
int birth = Integer.parseInt(birthString);
String currentString = JOptionPane.showInputDialog(
null, "Enter cureent year: ", "How long have you been alive?",
JOptionPane.QUESTION_MESSAGE);
int current = Integer.parseInt(currentString);
Pattern c = Pattern.compile("[A-Z,a-a,&%$#@!()*^]");
Matcher n = c.matcher(currentString);
if (n.find()){
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
如果有人输入除了数字以外的任何内容,它会给出对话框消息“这看起来不像我的数字......再试一次”,我想这样做。唯一的问题是它不会那样做,程序只是错误。任何帮助将不胜感激,我知道这是一个小的我做错了,只是找不到它。
答案 0 :(得分:1)
你想要匹配一年,为什么不使用更简单的正则表达式。 \\d+
将匹配一个或多个整数字符。 Matcher#matches会在完整的String
:
if (!birthString.matches("\\d+")) {
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
请参阅:Pattern