The question is as follows: Define a class MyDate (day, month, year) with methods to accept and display a MyDate object. Accept date as dd, mm, yyyy. Throw user defined exception "InvalidDateException" if the date is invalid. Examples of invalid dates:
12 15 2015
31 6 1990
29 2 2001
I wrote the following code but its not working in some instances. Please assist!
import java.util.*;
import java.util.Arrays;
import java.io.*;
class InvalidDateException extends Exception
{}
class MyDate
{
int day,month,year;
void accept()
{
try
{
Scanner S= new Scanner(System.in);
int d,m,y;
System.out.println("\nEnter day \nExample: 12 25 30 =>");
d=S.nextInt();
System.out.println("\nEnter month \nExample: 2 6 12 =>");
m=S.nextInt();
System.out.println("\nEnter year \nExample: 2012 2025 1930 =>");
y=S.nextInt();
//display(); for testing porposes
//System.out.println(valid(d,m,y)); for testing porposes
if(valid(d,m,y))
{
day=d;
month=m;
year=y;
}
else
{
throw new InvalidDateException();
}
}
catch(Exception e)
{
System.out.println("InvalidDateException");
}
}
boolean valid(int d,int m,int y)
{
int []m31=new int[]{1,3,5,7,8,10,12};
int []m30=new int[]{4,6,9,11};
//System.out.println("\n\t\t"+d+m+y); for testing porposes
if(Arrays.asList(m31).contains(m) && d<=31)
{
return true;
}
else if(Arrays.asList(m30).contains(m) && d<=30)
{
return true;
}
else if(y%4==0 && d<=29)
{
return true;
}
else if(y%4!=0 && d<=28)
{
return true;
}
else
{
return false;
}
}
void display()
{
System.out.println("DAY-MONTH-YEAR :: "+day+"-"+month+"-"+year);
}
}
class Main
{
public static void main(String args[])
{
MyDate date= new MyDate();
date.accept();
date.display();
}
}
While I have resolved the other issues, the program seems to not work for days above 29.
Its showing valid if day is below 30
And invalid for day above 29 changing month or year has no affect