Monday, 3 November 2014

Define class MyDate with members day, month, year. Define default and parameterized constructors. Accept values from the command line and create a date object. Throw user defined exceptions – “InvalidDayException” or “InvalidMonthException” if the day and month are invalid. If the date is valid, display message “Valid date”.





Name : Shreyal Mandot

Title : Assignment 4b1. Define class MyDate with members day, month, year. Define default and parameterized constructors. Accept values from the command line and create a date object. Throw user defined exceptions – “InvalidDayException” or “InvalidMonthException” if the day and month are invalid. If the date is valid, display message “Valid date”.



class MyDate
{

int day,month,year;

MyDate()
{

System.out.println("\nNo Date Initialised...");

}

MyDate(int d,int m,int y)
{

day=d;
month=m;
year=y;

}

boolean checkmonth()
{

if(month<1 || month >12)
return false;

else
return true;

}

boolean checkday()
{

boolean state;

if(day<1 || day>31 )
state=false;

else
{

switch (month)
{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:
if(day > 31)
{
 
  state= false;

}

else
state= true;break;

case 4:

case 6:

case 9:

case 11:
if(day > 30)
          {
         
          state= false;
         
          }
         
          else
          state= true;break;

case 2:
if(year % 4 != 0 && day > 28)
{
       
          state= false;
         
          }
         
          else
          return true;

if(day > 29)
        {
       
          state= false;
       
        }

default:
          state= false;

}

}

return state;
}

}

class InvalidDayException extends Exception
{

public InvalidDayException(String s)
{

super(s);

}

}

class InvalidMonthException extends Exception
{

public InvalidMonthException(String s)
{

super(s);

}

}

class ass4b1
{

public static void main(String args[])
{

int d1,m1,y1;

if(args.length != 3)
{

System.out.println("\nUse command line argument as:");
System.out.println("dd mm yyyy\n");

}

else
{

  d1=Integer.parseInt(args[0]);

y1=Integer.parseInt(args[2]);

  m1=Integer.parseInt(args[1]);

MyDate a =new MyDate(d1,m1,y1);

try
{

if(! a.checkmonth())
throw new InvalidMonthException("Month is  Invalid");

if(! a.checkday())
throw new InvalidDayException("Day is  Invalid");

System.out.println("\n Valid Date;");

}

catch(InvalidMonthException e)
{

System.out.println(e);

}

catch(InvalidDayException e)
{

System.out.println(e);

}

}

}

}

/*

Output-

[prady@localhost setB]$ javac ass4b1.java
[prady@localhost setB]$ java bass4b1

Use command line argument as:
dd mm yyyy

[prady@localhost setB]$ java bass4b1 01 02 2000

Valid Date;

[prady@localhost setB]$ java bass4b1 29 02 1999

InvalidDayException: Day is  Invalid

*/

No comments:

Post a Comment