根据Date的API实现一个SmartDate类型,在日期非法时抛出一个异常。
/**
* Description :
* Author : mn@furzoom.com
* Date : Sep 26, 2016 5:40:07 PM
* Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
*/
package com.furzoom.lab.algs.ch102;
/**
* ClassName : E10211 <br>
* Function : TODO ADD FUNCTION. <br>
* date : Sep 26, 2016 5:40:07 PM <br>
*
* @version
*/
public class E10211
{
public static void main(String[] args)
{
try {
SmartDate date = new SmartDate(13, 1, 1999);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
SmartDate date = new SmartDate(2, 29, 2000);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
SmartDate date = new SmartDate(2, 29, 1900);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
SmartDate date = new SmartDate(2, 28, 2002);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
SmartDate date = new SmartDate(4, 31, 2000);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
SmartDate date = new SmartDate(5, 31, 2000);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
class SmartDate
{
private final int month;
private final int day;
private final int year;
public SmartDate(int m, int d, int y)
{
if (!validate(m, d, y))
throw new IllegalArgumentException("Argument illegal " + m + "/" + d + "/" + y);
this.month = m;
this.day = d;
this.year = y;
}
public int month()
{
return month;
}
public int day()
{
return day;
}
public int year()
{
return year;
}
public String toString()
{
return month + "/" + day + "/" + year;
}
private boolean validate(int m, int d, int y)
{
if (y == 0 || y < -1000 || y > 10000)
return false;
if (m < 1 || m > 12)
return false;
if (d < 1 || d > 31)
return false;
int[] months = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (d > months[m])
return false;
if (!(y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)))
{
if (d > 28)
return false;
}
return true;
}
}
结果:
java.lang.IllegalArgumentException: Argument illegal 13/1/1999
at com.furzoom.lab.algs.ch102.SmartDate.<init>(E10211.java:68)
at com.furzoom.lab.algs.ch102.E10211.main(E10211.java:21)
java.lang.IllegalArgumentException: Argument illegal 2/29/1900
at com.furzoom.lab.algs.ch102.SmartDate.<init>(E10211.java:68)
at com.furzoom.lab.algs.ch102.E10211.main(E10211.java:33)
java.lang.IllegalArgumentException: Argument illegal 4/31/2000
at com.furzoom.lab.algs.ch102.SmartDate.<init>(E10211.java:68)
at com.furzoom.lab.algs.ch102.E10211.main(E10211.java:45)