2 回答

TA贡献1871条经验 获得超8个赞
发生这种情况是因为您break在IF范围内->如果年份不是1,则继续第3种情况。
您可以使用if else子句:
case 2:
if(year == 1) {
days = 29;
} else {
days = 28;
}
break;
但是我要提醒您,year != 1这并不意味着它的2月获得28天,也许您想要这样:
case 2:
if(!isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;

TA贡献1946条经验 获得超3个赞
除了关于if语句和的switch问题外,首先使用leap年检查的方法还需要解决一些问题。这是下面原始代码的开头:
public static boolean isLeapYear(int year) {
if(year < 1 && year > 9999) {
return false;
} else {
...
这种情况year < 1 && year > 9999永远不会发生,因为year不能同时小于1和大于9999,所以这是多余的。
除此之外,用于确定年份是否为a年的算法如下(以纯英语显示):
看看该年份是否可以被4整除。如果不是,则该年份不能是a年(返回false)。
在这里,一年可以平均除以4(在步骤1中确定)。如果不能被100整除,则为is年(返回true)。
在这里,年份可以被4除以100,也可以除以100。如果该年份也可以被400除以,那么它就是leap年。否则不是。
将以上所有考虑因素放入代码中,可以使其更具可读性:
public static boolean isLeapYear(int year) {
if (year % 4 != 0) {
// year is not evenly divisible by 4 (it has a remainder, can't be a leap year).
return false;
}
// year is evenly divisible by 4
if (year % 100 != 0) {
// divisible by 4 and not 100, it's a leap year
return true;
}
// divisible by 4 and also 100
if (year % 400 != 0) {
// divisible by 4, 100 and not by 400
return false;
}
// divisible by 4, 100 and 400
return true;
}
考虑到您的getDaysInMonth方法,我们有以下情况,其中1 =一月,2 =二月,依此类推:
30天:9月(9),4月(4),6月(6),11月(11)
31天:除2月(2)以外的所有其他日子(a年28、29)
public static int getDaysInMonth(int month, int year) {
switch (month) {
case 9:
case 4:
case 6:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return 31;
}
}
关于参数的验证,如果您正在接收用户输入,则应在用于计算的方法之外对所有参数进行验证(传递已被验证的方法输入,而不是直接在其中进行验证)。
添加回答
举报