【问题标题】:Data validation within data validation数据验证中的数据验证
【发布时间】:2014-10-04 17:11:27
【问题描述】:

我首先要验证用户是否输入了一个值,并确保在按下“取消”时退出。然后,我想在将 String 转换为 java.sql.Date 的同时验证 String releaseDateString 的格式是否正确。

第一次验证正在发生,但随后 JOptionPane 继续重复自己,甚至不考虑跟随它的 try 和 catch。

这是我的方法

boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";

while (!retry) {
   while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
      releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
      qtd.stringValidation(releaseDateString);  
   }
   try { //the date is validated to make sure it is in the correct format
      releaseDate = java.sql.Date.valueOf(releaseDateString);
   } catch (Exception e) {
      retry = false;
      JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
   }
}

链接到这个方法

public static boolean stringValidation(String attribute){
   boolean retry = false;
   if (attribute == null){
      System.exit(0);
   }
   else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the 
   {
      JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
   }
   else {
      retry = true;
   }
   return retry;          
}

【问题讨论】:

  • 这与问题无关,但stringValidation是静态方法。如果qtd 是一个实例,您可能不应该通过qtd 访问它。您应该通过您的班级访问它,例如:MyClass.stringValidation
  • qtd 实际上是同一个包中另一个类的名称,但无论如何感谢。
  • 那是一个非常糟糕的命名约定。 Java 中的类名遵循 Pascal Case 命名约定,并且应该以大写字母开头。你目前的模式会让每个人都感到困惑。

标签: java validation if-statement while-loop


【解决方案1】:

当你这样做时,

qtd.stringValidation(releaseDateString); 

您没有将结果分配给retry。我相信你想要,

retry = qtd.stringValidation(releaseDateString);

【讨论】:

  • 好答案。 1+ 来反驳我最近的反对票。再次抱歉。
猜你喜欢
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2017-07-20
  • 2022-01-15
  • 2010-11-15
相关资源
最近更新 更多