代码之家  ›  专栏  ›  技术社区  ›  user2278017

JoptionPane验证出现问题

  •  1
  • user2278017  · 技术社区  · 12 年前

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

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

    我想确保,如果有人输入了数字以外的任何东西,它会显示对话框消息“对我来说这不像数字…再试一次”。唯一的问题是它没有做到这一点,程序只是出错了。任何帮助都将不胜感激,我知道这是我做错的小事情,只是找不到。

    1 回复  |  直到 12 年前
        1
  •  1
  •   Reimeus    12 年前

    您正在尝试匹配年份,为什么不使用更简单的正则表达式呢。 \\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