我知道这是不正确的,但我无法弄清楚。我只需要改变我的整个方法吗?这个网站也说这个问题已经被问过,但他们都没有帮助我。
public Date(int cMonth, int cDate, int cYear, int cDayToDate, String cStrMonth, int dayYear){
if (cMonth = 01 && 12){
month = cMonth;
if (cMonth = 01,03,05,07,08,10,12){
if (cDate <= 31 ){
date = cDate;
}// end of if
}// end of if(cMonth) months with 31 days
else if(cMonth = 04, 06, 09, 11){
if (cDate <=30){
date = cDate;
}
}// end of cMonth month within 30 days
最佳答案
switch 语句可能最适合这种情况。
public Date(int cMonth, int cDate, int cYear, int cDayToDate, String cStrMonth, int dayYear) {
switch (cMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (cDate > 31)
throw new IllegalArgumentException();
break;
case 4:
case 6:
case 9:
case 11:
if (cDate > 30)
throw new IllegalArgumentException();
break;
case 2:
int days = isLeapYear(cYear) ? 29 : 28;
if (cDate > days)
throw new IllegalArgumentException();
break;
default:
throw new IllegalArgumentException();
}
date = cDate;
}
更接近您要求的东西,但效率却低得多
public Date(int cMonth, int cDate, int cYear, int cDayToDate, String cStrMonth, int dayYear) {
if (Arrays.asList(1, 3, 5, 7, 8, 10, 12).contains(cMonth)) {
if (cDate > 31)
throw new IllegalArgumentException();
} else if (Arrays.asList(4, 6, 9, 11).contains(cMonth)) {
if (cDate > 30)
throw new IllegalArgumentException();
} else if (cMonth == 2) {
int days = isLeapYear(cYear) ? 29 : 28;
if (cDate > days)
throw new IllegalArgumentException();
} else {
throw new IllegalArgumentException();
}
date = cDate;
}
顺便说一句,以 0
开头的数字是八进制,因此 08
和 09
无效。
关于java - 嗨,我试图让我的 if 语句等于多个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553608/