我是新的Java和所有此函數的參數/對象方法(與PowerShell非常不同) 我想寫一個代表Date對象的簡單程序,並且在每個set
之前,它檢查日期是否有效。如果無效,請設置爲默認值。在兩個不同函數中更改前驗證日期
我遇到了setDay
,setMonth
和setYear
(僅爲例子,下面只寫setYear
)有問題。與一個參數(年)一起工作的setYear
和使用3個參數(日,月,年)的isValidDate
。如何在設定的功能中調用isValidDate
?
我不能更改main
,但只有public/private
函數調用。
設定功能:
public void setYear(int yearToSet){
_year = isValidDate(yearToSet); //??????? PROBLEM ??????? tried:_year = isValidDate(yearToSet) ? yearToSet : DEF_YEAR;
_year = yearToSet;
}
計劃:
public class Date {
// Private vars
private int _day;
private int _month;
private int _year;
// Private finals
private final int MIN_DAY = 1;
private final int MIN_MONTH = 1;
private final int MAX_MONTH = 12;
private final int MIN_YEAR = 1000;
private final int MAX_YEAR = 9999;
private final int DEF_DAY = 1;
private final int DEF_MONTH = 1;
private final int DEF_YEAR = 2000;
// Constructors:
/**
* Creates a new Date object if the date is valid, otherwise creates the date 1/1/2000
* @param day the day in the month(1-31)
* @param month the month in the year(1-12)
* @param year the year (4 digits)
*/
public Date(int day, int month, int year) {
if (isValidDate(day,month,year)) {
_day = day;
_month = month;
_year = year;
}
else
defDate();
}
// Private methods
/**
* Set date to default - 1/1/2000
*/
private void defDate(){
setDay(DEF_DAY);
setMonth(DEF_MONTH);
setYear(DEF_YEAR);
}
/**
* Validate day by month
*/
private int numDaysInMonth(int month, boolean isLeapYear) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear) {
return 29;
} else {
return 28;
}
default:
return 0;
}
}
/**
* Leap year check
*/
private boolean isLeapYear(int year) {
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
/**
* Date validate
*/
private boolean isValidDate(int day, int month, int year) {
return (month >= MIN_MONTH && month <= MAX_MONTH) &&
(day >= MIN_DAY && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= MIN_YEAR && year <= MAX_YEAR);
}
/**
* Sets the year (only if date remains valid)
* @param yearToSet - the year value to be set
*/
public void setYear(int yearToSet){
_year = isValidDate(yearToSet); //??????? PROBLEM ???????
_year = yearToSet;
}
nooooo,幾個類已經可以做到......爲什麼試圖重新發明輪子? –
我知道,這是一個研究項目。我們不能使用這些類。 – igor