The problem I'm having is with this code:
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);
}
I wanted to make it to if someone input anything other than number that it would give the dialog message "That doesn't look like numbers to me... Try again". Only problem is that it doesn't do that, the program just errors. Any help would be appreciated, I know it's something small I'm doing wrong and just can't find it.
You're trying to match a year, why not use a simpler regular expression. \\d+
will match one or more integer characters. Matcher#matches will do a match on the full 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);
}
See: Pattern