In this chapter, the class dateType was designed to implement the date in a prog
ID: 3859743 • Letter: I
Question
In this chapter, the class dateType was designed to implement the date in a program, but the member function setDate and the constructor do not check whether the date is valid before storing the date in the member variables. Rewrite the definitions of the function setDate and the con- structor so that the values for the month, day, and year are checked before storing the date into the member variables. Add a member function, isLeapYear, to check whether a year is a leap year. Moreover, write a test program to test your class.
Explanation / Answer
Mydate.java
package com.charan;
public class Mydate {
boolean b1,b2,b3;
private int day,month,year;
public Mydate(int day, int month, int year) {
super();
setMonth(month);
setDay(day);
setYear(year);
isValid();
}
public void isValid()
{
if(b1==true && b2==true&& b3==true)
{
System.out.println(" date is valid");
}
}
public int getYear() {
return year;
}
public void setYear(int year) {
if(year>=0)
{
this.year = year;
b1=true;
}
else
{
System.out.println(" year is not valid");
}
}
public int getDay() {
return day;
}
public void setDay(int day)
{
if(getMonth()==2)
{
if(day>=0 && day<=29)
{
b2=true;
}
else
{
System.out.println("date is not valid");
}
}
else if((day>=1)&&(day<=31))
{
this.day = day;
b2=true;
}
else
{
System.out.println(" you enterd day is not valid");
}
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if(month<=12)
{
this.month = month;
b3=true;
}
else
{
System.out.println(" your enterd month is not valid");
}
}
public boolean isLeapYear(int year)
{
boolean isLeap = false;
if(year % 400 == 0)
{
isLeap = true;
}
else if (year % 100 == 0)
{
isLeap = false;
}
else if(year % 4 == 0)
{
isLeap = true;
}
else
{
isLeap= false;
}
return isLeap;
}
}
Test.java
package com.charan;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("please enter day: ");
int day=sc.nextInt();
System.out.print("please enter month: ");
int month=sc.nextInt();
System.out.print("please enter year: ");
int year=sc.nextInt();
Mydate obj=new Mydate(day,month,year);
System.out.println(" "+year+" is leap year :" +obj.isLeapYear(year));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.