我寫了一個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);
}
}
*我做了頌歌* ????? – 2011-02-23 11:11:17
你真的應該使用更多的**描述性標題**。我們已經可以看到它是關於標籤中的Java,如果你不需要幫助,你就不會在這裏發佈吧? – 2011-02-23 11:11:26
+1這個問題的描述方式是「代碼」有自己的想法! – zengr 2011-02-23 11:11:51