使用Try Catch在构造函数中进行日期验证

时间:2016-12-10 05:01:28

标签: java

我需要制作一个Date课程,在这个Date课程中,我需要一个能够在&#34中验证日期的构造函数; mm / dd / yyyy &# 34;格式。此外,如果构造函数的参数与日期格式不匹配,则需要抛出类型Exception的异常。该类要求字段month,day和year为整数。如果传入参数不符合日期格式,我需要将所有字段设置为0.

对于我的生活,我无法抓住例外。任何帮助将不胜感激。

public class Date 
{
   private int month;
   private int day;
   private int year;
   private String date;

   public Date(String aDate)
   {
      date = aDate;
      String[] str = date.split("/");
      String sMonth = str[0];
      String sDay = str[1];
      String sYear = str[2];
      month = Integer.parseInt(sMonth);
      day = Integer.parseInt(sDay);
      year = Integer.parseInt(sYear);

      try
      {
          if (month <= 12 && day <= 31)
          {
              month = month;
              day = day; 
          }
          if (sYear.length() != 4)
          {
          year = year;
          }
      }
      catch (Exception e)
      {
         month = 0;
         day = 0;
         year = 0; 
      }      
 }
}

2 个答案:

答案 0 :(得分:1)

首先转换为int:

date = aDate;
String[] str = date.split("/");
String sMonth = str[0];
String sDay = str[1];
String sYear = str[2];

try
{
    // Here you compare String to an int, do the convertions to int first
    // to make it throw exception on non integers.
    if (month <= 12 && day <= 31)
    {
        month = month = Integer.parseInt(sMonth);
        day = Integer.parseInt(sDay); 
    }
    if (sYear.length() != 4)
    {
    year = Integer.parseInt(sYear);
    }
}
catch (Exception e)
{
   month = 0;
   day = 0;
   year = 0; 
}

更新

您需要验证自己。它需要比下面更多的验证,但只是一个提示。

try {
    // These can throw exceptions and you want to catch those too.
    month = Integer.parseInt(sMonth);
    day = Integer.parseInt(sDay);
    year = Integer.parseInt(sYear);

    if (month <= 12) {
        throw new Exception("month");
    }
    if (day <= 31) {
        throw new Exception("day");
    }    
    if (sYear.length() != 4) {
        throw new Exception("year");
    }
} catch (Exception e) {
    month = 0;
    day = 0;
    year = 0;
}

答案 1 :(得分:0)

Java包含许多可以帮助您的库。 访问:https://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

但如果真的需要构造函数,则需要添加更多验证。

date = aDate;
String[] str = date.split("/");
String sMonth = str[0];
String sDay = str[1];
String sYear = str[2];

// Aux Variables
Integer m;
Integer d;

try {
    // Parse to Int, 
    // if Integer.parseInt cannot parse an Exception will be throw
    m = Integer.parseInt(sMonth);
    d = Integer.parseInt(sDay);

    // Check if months is in [1 - 12] range
    // Check if days is in [ 1 - 31] (You can add extra validations, i.e. for February)
    if (m > 0 && m <= 12 && d > 0 && d <= 31) {
        month = m
        day = d
    }

    if (sYear.length() != 4) {
        year = Integer.parseInt(sYear);
    }

} catch (Exception e) {
   month = 0;
   day = 0;
   year = 0; 
}