I added to my code a new array \(\displaystyle \text{daysPerMonth}\) to include the days of each month. I also added \(\displaystyle 7\) methods:
\(\displaystyle \text{setDate}\)
\(\displaystyle \text{setDay}\)
\(\displaystyle \text{setMonth}\)
\(\displaystyle \text{setYear}\)
\(\displaystyle \text{getDay}\)
\(\displaystyle \text{getMonth}\)
\(\displaystyle \text{getYear}\)
With those methods, the date will get validated before it is printed. If the date is wrong, the program will tell you that \(\displaystyle \text{Wrong day}\) or \(\displaystyle \text{Wrong year}\). If the month is wrong, you will get a runtime error. If the date is wrong, the program will print the default values of \(\displaystyle \text{day}\) and \(\displaystyle \text{year}\) which is zero. In the next post, we will fix the \(\displaystyle \text{month}\) runtime error and the printed default values of \(\displaystyle \text{day}\) and \(\displaystyle \text{year}\).
I tested this date:
\(\displaystyle \text{Date(day,month,year)} = \text{Date(29,2,-111)} = 0/2/0\)
Here the code so far with a screenshot:
package Moon;
public class Date {
int day;
int month;
int year;
int daysPerMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
public Date(int day, int month, int year){
setDate(day,month,year);
}
public void setDate(int d, int m, int y){
setDay(d,m);
setMonth(m);
setYear(y);
}
public void setDay(int d, int m){
if (d > 0 && d <= daysPerMonth[m]){
this.day = d;
} else {System.out.println("Wrong day.");}
}
public void setMonth(int m){
if (m > 0 && m <= 12){
this.month = m;
} else {System.out.println("Wrong month.");}
}
public void setYear(int y){
if (y > 0){
this.year = y;
} else {System.out.println("Wrong year.");}
}
public int getDay(){
return day;
}
public int getMonth(){
return month;
}
public int getYear(){
return year;
}
public String toString(){
return String.format("%d/%d/%d",getDay(),getMonth(),getYear());
}
public static void main(String[] args){
Date date = new Date(29,2,-111);
System.out.println("My birthdate is : " + date);
}
}
