我写了一个if
语句,应该根据数据写出不同的输出。它在 时有效int y = 2000, m = 5, d = 06;
,但是在 时不输出正确的值int y = 2889, m = 44, d = 16;
。
这是我的代码。有人可以帮我理解什么是错的。
public class Date1 {
private int year = 1; // any year
private int month = 1; // 1-12
private int day = 1; // 1-31 based on month
//method to set the year
public void setYear(int y) {
if (y <= 0) {
System.out.println("That is too early");
year = 1;
}
if (y > 2011) {
System.out.println("That year hasn't happened yet!");
y = 2011;
} else {
year = y;
}
}
public int setMonth(int theMonth) {
if ( theMonth > 0 && theMonth <= 12 ) { // validate month
return theMonth;
} else { // month is invalid
System.out.printf("Invalid month (%d) set to 1.", theMonth);
return 1; // maintain object in consistent state
} // end else
}
public int setDay( int theDay) {
int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// check if day in range for month
if ( theDay > 0 && theDay <= daysPerMonth[ month ] ) {
return theDay;
}
// check for leap year
if ( month == 2 && theDay == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) {
return theDay;
}
System.out.printf( "Invalid day (%d) set to 1.", theDay );
return 1; // maintain object in consistent state
}
//method to return the year
public int getYear() {
return year;
}
//method to return the month
public int getMonth(){
return month;
}
//method to return the day
public int getDay(){
return day;
}
// return a String of the form year/month/day
public String toUniversalStringTime() {
return String.format( "The date using a default constructor %d/%d/%d \n", getYear(), getMonth(), getDay() );
} // end toUniversalStringTime
}
public class Date1Test {
public static void main(String[] args) {
int y = 2000, m = 5, d = 06;
Date1 d1 = new Date1(); //create a new object
System.out.println(d1.toUniversalStringTime()); //call toUniversalStringTime()
System.out.printf("The date I created is %d/%d/%d \n", y , m , d);
}
}