DEVELOP A DATE CLASS
AIM:
To write a java program to develop a
date class.
ALGORITHM:
1.
Declare all the required variables.
2, In date constructor check we give
the valid date or not.If not valid date display the exception
else get the input.
3. In the invalid function check
whether the month,days are valid or not.
4
In the leap year function check whether the year is leap or not.
5
Use toString method convert the object to string .
6. In the main function call the
corresponding function by creating the object and then display the
result.
PROGRAM:
import
java.io.*;
import
java.util.*;
public class
Date
{
private final int month;
private final int day;
private final int year;
public Date(int m,int d,int y)
{
if(!isValid(m,d,y))throw
new RuntimeException("Invalid");
month=m;
day=d;
year=y;
}
private static boolean isValid(int
m,int d,int y)
{
int[]
DAYS={0,31,29,31,30,31,30,31,31,30,31,30,31};
if(m<1||m>12)return
false;
if(d<1||d>DAYS[m])return
false;
if(m==2 && d==29
&& !isLeapYear(y))return false;
return true;
}
private static boolean isLeapYear(int y)
{
if(y%400==0)return
true;
if(y%100==0)return
false;
return(y%4==0);
}
public Date next()
{
if(isValid(month,day+1,year))return
new Date(month,day+1,year);
else
if(isValid(month+1,1,year))return new Date(month+1,1,year);
else
return new Date(1,1,year+1);
}
public String toString()
{
return
month+"-"+day+"-"+year;
}
public static void main(String[] args)
{
try
{
InputStreamReader
isr=new InputStreamReader(System.in);
BufferedReader bf=new
BufferedReader(isr);
System.out.println("Enter
month,date and year in the format mm/dd/yyyy");
String
d=bf.readLine();
int
da[]=new int[3];
String
str1[]=new String[3];
str1=d.split("/");
for(int i=0;i<3;i++)
{
da[i]=Integer.parseInt(str1[i]);
}
Date
today=new Date(da[0],da[1],da[2]);
System.out.println(today);
Date
nextDate=today.next();
System.out.println(nextDate);
}
catch(Exception
e)
{
System.out.println(e);
}
}
}
OUTPUT:
Enter
month,Date,year in the format mm//dd/yyy
12/31/2000
12-31-2000
1-1-2001
RESULT:
Thus the java program to develop a date class was implemented
Thus the java program to develop a date class was implemented
No comments:
Post a Comment