我是Java新手,以及所有这个函数param / object方法(与PowerShell非常不同)
我想编写一个表示Date对象的简单程序,在每个set
之前,它会检查日期是否有效。如果它无效,请设置为默认值。
我在使用setDay
,setMonth
和setYear
时遇到问题(仅针对该示例在下面仅编写setYear
)。 setYear
使用一个参数(年),isValidDate
使用3个参数(日,月,年)。如何在集合函数中调用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;
}
答案 0 :(得分:2)
isValidDate返回一个布尔值,_year是一个int,所以你不能写:
<?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>
<tag>Tag1</tag>
<text>Note1</text>
<dateTimeUtc>2015-04-05T18:14:13Z</dateTimeUtc>
<textCursorPosition>183</textCursorPosition>
</note>
<note>
<tag>Tag2</tag>
<text>Note2</text>
<dateTimeUtc>2015-04-05T18:09:05Z</dateTimeUtc>
<textCursorPosition>504</textCursorPosition>
</note>
<note>
<tag>Tag2</tag>
<text>Note2</text>
<dateTimeUtc>2015-04-05T18:09:05Z</dateTimeUtc>
<textCursorPosition>504</textCursorPosition>
</note>
</notes>
你可以写:
_year = isValidDate(yearToSet)
或一行:
if (isValidDate(_day,_month,yearToSet) {
_year = yearToSet;
} else {
_year = DEF_YEAR;
}
你犯了两个错误: