我有一个方法,根据用户给出的输入定义季节。 例:1/6 =冬天 它工作,但似乎应该有一个更简单的方法来做到这一点,而不是拥有所有这些代码。有什么建议吗?
public String getSeason()
{
String result = "UNKNOWN";
if (month == 1 && day >= 1)
{
result = "WINTER";
}
else if (month == 2 && day >= 1)
{
result = "WINTER";
}
else if (month == 3 && day <= 20)
{
result = "WINTER";
}
else if (month == 3 && day >= 21)
{
result = "SPRING";
}
else if (month == 4 && day >= 1)
{
result = "SPRING";
}
else if (month == 5 && day >= 1)
{
result = "SPRING";
}
else if (month == 6 && day <= 20)
{
result = "SPRING";
}
else if (month == 6 && day >= 21)
{
result = "SUMMER";
}
else if (month == 7 && day >= 1)
{
result = "SUMMER";
}
else if (month == 8 && day >= 1)
{
result = "SUMMER";
}
else if (month == 9 && day <= 22)
{
result = "SUMMER";
}
else if (month == 9 && day >= 23)
{
result = "FALL";
}
else if (month == 10 && day >= 1)
{
result = "FALL";
}
else if (month == 11 && day >= 1)
{
result = "FALL";
}
else if (month == 12 && day <= 20)
{
result = "FALL";
}
else if (month == 12 && day >= 21)
{
result = "FALL";
}
return result;
}
答案 0 :(得分:4)
使用switch
。
switch (month) {
case 1: case 2: /* Winter */; break;
case 3: if (day <= 20) {/* Winter */} else {/* Spring */} break;
case 4: case 5: /* Spring */; break;
case 6: if (day <= 21) {/* Spring */} else {/* Summer */} break;
// Continue the pattern...
default: /* Unknown */; break;
}
这比if-else
阶梯要好得多,因为它很简单。 break;
语句使程序不会“掉头”并执行每一个案例。
答案 1 :(得分:2)
你可以通过抛弃不必要的day >= 1
(它还能做什么?)并将几个月结合起来来缩短它:
if (month <= 2 || (month == 3 && day <= 20) || (month == 12 && day >= 21)) {
// Winter
} else if (month <= 5 || (month == 6 && day <= 21)) {
// Spring
} else if (month <= 8 || (month == 9 && day <= 22)) {
// Summer
} else {
// Fall
}
答案 2 :(得分:0)
这是使用Java Calendar类查看问题的另一种方法。例如(未经测试的代码)当你进行闰年检测时,它会变得有点复杂,但正如我所说,这是一种不同的方式来思考这个问题。
public String testSeason(int year, int month, int day) {
//month is 0 based!
int FIRST_DAY_OF_SPRING = 31 + 28 + 21; // might need leap year detection to be completely accurate.
int FRIRST_DAY_OF_SUMMER = FRST_DAY_OF_SPRING + 10 + 31 + 30 +31;
// define FALL and WINTER similarly.
Calendar testDate = new Calendar();
testDate.set(year,month,day);
if (testDate.get(Calendar.DAY_OF_YEAR) < FIRST_DAY_OF_SPRING) return "Winter";
if (testDate.get(Calendar.DAY_OF_YEAR) < FIRST_DAY_OF_SUMMER) return "Spring";
// continue for rest of seasons.
}