2013-04-13 37 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