Program in Java
PROGRAM DESIGN
Create a class Date that can perform the following operations on a date:
- Set/Return the Month
- Set/Return the Day
- Set/Return the Year
- Whether the year is a leap year.
if the year number isn't divisible by 4, it is a common year;
otherwise, if the year number isn't divisible by 100, it is a leap year;
otherwise, if the year number isn't divisible by 400, it is a common year;
otherwise, it is a leap year.
- Return the number of days in a month
April, June, September, November has 30 days otherwise 31 except for Feb (refer to leap year)
- Print the month in string format followed by the date and year
SAMPLE INPUT1
2020
2
15
SAMPLE OUTPUT1
February 15, 2020
29 days
2020 is a Leap Year
SAMPLE INPUT2
2019
2
29
SAMPLE OUTPUT2
Invalid number of days
SAMPLE INPUT3
2019
3
15
SAMPLE OUTPUT3
March 15, 2019
31 days
2019 is a Common Year
import java.util.*;
class Date {
private int day, month, year;
private int days_per_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private String monthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
public Date(int month, int day, int year) {
this.day = day;
this.month = month;
this.year = year;
}
/**
* if the year number isn't divisible by 4, it is a common year;
*
* otherwise, if the year number isn't divisible by 100, it is a leap year;
*
* otherwise, if the year number isn't divisible by 400, it is a common year;
*
* otherwise, it is a leap year.
*
* @param year
* @return
*/
boolean isLeapYear(int year) {
return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
public String toString() {
String leapYear = "Common Year";
int days = days_per_month[this.month - 1];
if (this.day > days) {
return "Invalid number of days";
}
if (isLeapYear(year)) {
leapYear = "Leap Year";
if (this.month == 2) {
days = 29;
if (this.day > days) {
return "Invalid number of days";
}
}
}
return monthNames[this.month - 1] + " " + day + ", " + year + "\n" + days + " days\n" + year + " is a "
+ leapYear;
}
// Setters and getters,
/**
* @return the day
*/
public int getDay() {
return day;
}
/**
* @param day the day to set
*/
public void setDay(int day) {
this.day = day;
}
/**
* @return the month
*/
public int getMonth() {
return month;
}
/**
* @param month the month to set
*/
public void setMonth(int month) {
this.month = month;
}
/**
* @return the year
*/
public int getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(int year) {
this.year = year;
}
}
class App {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int year = keyboard.nextInt();
int month = keyboard.nextInt();
int day = keyboard.nextInt();
Date d = new Date(month, day, year);
System.out.println(d.toString());
keyboard.close();
}
}
Comments
Leave a comment