64 570
Assignments Done
99,2%
Successfully Done
In September 2018

Answer to Question #70519 in Java | JSP | JSF for Atif Haroon

Question #70519
( Date Class) Create a class called Date that includes three instance variablesa month (type int ),
a day (type int ) and a year (type int ). Provide a constructor that initializes the three instance
variables and assumes that the values provided are correct. Provide a set and a get method for each
instance variable. Provide a method displayDate that displays the month, day and year separated
by forward slashes ( / ). Write a test application named DateTest that demonstrates class Date s
capabilities.
Expert's answer
public class Date {

private final static int DEFAULT_MONTH= 1;
private final static int DEFAULT_DAY= 1;

private int month;
private int day;
private int year;

private boolean checkMonth(int month) {
return month >= 1 && month <= 12;
}

private boolean checkDay(int day) {
return day >= 1 && day <= maxDay();
}

private int maxDay() {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return 31;
case 4:
case 6:
case 9:
case 11: return 30;
case 2: return (year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0)
? 29 : 28;
default: return 31;
}
}

public Date(int month, int day, int year) {
this.year = year;
this.month = checkMonth(month) ? month : DEFAULT_MONTH;
this.day = checkDay(day) ? day : DEFAULT_DAY;
}

public int getMonth() {
return month;
}

public void setMonth(int month) {
this.month = checkMonth(month) ? month : DEFAULT_MONTH;
}

public int getDay() {
return day;
}

public void setDay(int day) {
this.day = checkDay(day) ? day : DEFAULT_DAY;
}

public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public void displayDate() {
System.out.println(month + "/" + day + "/" + year);
}

}




public class DateTest {

public static void main(String[] args) {

Date date = new Date(8, 17, 2013);

System.out.print("Date: ");
date.displayDate();
System.out.println();

System.out.println("month = " + date.getMonth());
System.out.println("day = " + date.getDay());
System.out.println("year = " + date.getYear());

date.setMonth(3);
date.setDay(25);
date.setYear(2001);

System.out.println();
System.out.print("New date with correct input: ");
date.displayDate();

date.setMonth(100);
date.setDay(-45);

System.out.println();
System.out.print("New date with incorrect input (default values): ");
date.displayDate();

}

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions