【问题标题】:Java - Input VerifierJava - 输入验证器
【发布时间】:2013-11-28 03:14:36
【问题描述】:

我只是创建这个特定的,但我对记录这个有点困惑。我只是坚持解释最后几行的作用:

class MyVerifier extends InputVerifier {

public boolean verify(JComponent input) {

  if (input==id) {
    return validId();

}

 else if (input==name) {
     return validName();

 }

 return false;
}

    public boolean validId() {
      boolean status;
      String theID = id.getText();
      Pattern pattern = Pattern.compile("\\d{8}");
      Matcher matcher = pattern.matcher(theID);
      if (matcher.matches()) {
          status = true;
      }
      else {
          status = false;
      }
       return status;
    }
    public boolean validName() {
       boolean status;
       String theName = name.getText();
       Pattern pattern = Pattern.compile("[A-za-z0-9 ]+");
       Matcher matcher = pattern.matcher(theName);
       if (matcher.matches()) {
           status = true;
       }
       else {
           status = false;
       }
       return status;
    }
}

你能在这里一一解释这些具体的行吗?

/**
 * @param  o    the object corresponding to the user's selection
 */
@Override
public void tell(Object o) { -- Where has this come from ?
    deptCode.setText(o.toString());
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == submit) {
        MyVerifier test = new MyVerifier();

        if (Staff.getStaff(id.getText()) == null && test.verify(id) &&
                test.verify(name)) {
            System.out.println("YAY");-- What is this doing
        }
        else if (!(Staff.getStaff(id.getText()) == null)) {
            String errorMessage = "ID EXISTS: " + Staff.getStaff(id.getText()).toString(); -- What is this doing

            JOptionPane.showMessageDialog(theFrame, errorMessage, "Error",
                JOptionPane.WARNING_MESSAGE);-- What is this doing
        }
        else {
            System.out.println("Woops.");
        }
    }

    else if (e.getSource() == clear) {
        id.setText(null);
        deptCode.setText(null);
        name.setText(null);
    }
}

public static void main(String[] args) {
    Registration test = new Registration();
}
}

【问题讨论】:

  • 如果是你自己写的,你怎么不知道它们的意思?你为什么写它们?
  • @MaurícioLinhares Aliens
  • System.out.println("YAY");;我们真的需要解释这是做什么的吗?
  • 您的实际问题是什么?
  • 是的,我会继续说,如果你不能解释这一点,那么你就没有写它。我也不认为任何人都可以告诉你,如果没有完整的,这到底是做什么的程序的上下文,因为它看起来涉及一些图形。

标签: java validation inputverifier


【解决方案1】:

既然您已经了解了您要通过该程序完成的工作,请从头开始(如有必要,请以您的第一次尝试为例)。重新开始通常比修复程序更容易。

【讨论】:

    【解决方案2】:

    您的public void tell(Object o) 方法似乎正在使用传递的对象的值设置一个字符串。但是,因为您还没有向我们展示您使用它的目的,所以我们无法确定。另一方面,您的其他问题相当清楚:

    System.out.println("YAY");

    Staff.getStaff(id.getText) 似乎正在检查字符串或文本文件中的名称和 ID 列表。仅当以前没有使用提供的 idname 创建工作人员时,此语句才会打印“YAY”。但是由于您还没有向我们展示这些变量在哪里,这只是我最好的猜测。

    JOptionPane.showMessageDialog(theFrame, errorMessage, "Error", JOptionPane.WARNING_MESSAGE);

    如果已经有工作人员使用给定的idname,则会显示JOptionPane 警告消息。显然,您无法创建其他人拥有的帐户,因此如果确实如此,则此 JOptionPane 会显示错误消息。

    【讨论】: