2013-04-13 33 views
1

我遇到的问题是这段代码有麻烦:与JOptionPane的验证

 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

你想匹配一年,为什么不使用更简单的正则表达式。 \\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

+0

没错,就是做到了。要回答你的问题,我在Java中很新,所以不知道这一点。无论如何,感谢您的快速回复和帮助。我几乎可以将这个简单的小程序完成,然后继续工作,以帮助我学习。 – user2278017