1

我遇到的问题是这段代码:

       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);
   }

如果有人输入除数字以外的任何内容,我想做到这一点,它会给出对话框消息“这对我来说看起来不像数字......再试一次”。唯一的问题是它没有这样做,程序只是错误。任何帮助将不胜感激,我知道这是我做错的小事,只是找不到。

4

1 回答 1

1

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

于 2013-04-13T18:12:05.743 回答