简体   繁体   English

JoptionPane验证遇到问题

[英]Having trouble with JoptionPane Validation

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. \\\\d+将匹配一个或多个整数字符。 Matcher#matches will do a match on the full String : 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);
}

See: Pattern 另请: 模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM