meert meert - 1 month ago 8
Java Question

The next day App in Java

I need to write a Java program (class NextDay) that calculates and prints the date of the next day by entering the day, month, and year.

Sample call and output:

Actual Date 12.12.2004
The next day is the 13.12.2004.


The input should also be checked for correctness! If an erroneous date constellation (e.g., 32 12 2007) has been entered, the exception
InvalidDateArgumentsException
is to be thrown. Define this class in a suitable form as a subclass of the class
java.lang.Exception
.

I started to creating it but the problem is; i cant tell that < or > in switch statements.What should i do? Here are my classes:

public class Date {
private int day;
private int month;
private int year;


public Date(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}

public Date getNextDay() throws Exception{
if(isLeapYear() == true){
switch(month){

case 1: day = 31;
break;

case 2: day = 29;
break;

case 3: day = 31;
break;

case 4: day = 30;
break;

case 5: day = 31;
break;

case 6: day = 30;
break;

case 7: day = 31;
break;

case 8: day = 31;
break;

case 9: day = 30;
break;

case 10: day = 31;
break;

case 11: day = 30;
break;

case 12: day = 31;
break;
}


}
return new Date(day + 1, month, year);

}








public int getDay(){
return day;
}

public int getMonth(){
return month;
}

public int getYear(){
return year;
}

public boolean isLeapYear(){
if(year % 4 == 0 && year % 100 != 0 && year % 400 == 0){
return true;
}
return false;
}


public String toString(){
return this.day + "." + this.month + "." + this.year;
}
}



public class NextDay {

public static void main(String args[]) throws Exception {
Date dateObj = new Date(20, 5, 2016);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}

Answer

EDIT since we can't just use standard classes

If you have to use switch case, you should use it to set max day in current month and then check, if your current day more than this max day:

int maxDay;
switch (month) {
case 1: maxDay = 31; break;
case 2: maxDay = isLeapYear() ? 29 : 28; break;
case 3: maxDay = 31; break;
// ... other months ...
case 12: maxDay = 31; break;
default: throw new InvalidDateArgumentsException();
}
if (isLeapYear()) {
    maxDay = 29;
}
if (day > maxDay) {
    throw new InvalidDateArgumentsException();
}
Comments