java - 嗨,我试图让我的 if 语句等于多个数字

标签 java if-statement

我知道这是不正确的,但我无法弄清楚。我只需要改变我的整个方法吗?这个网站也说这个问题已经被问过,但他们都没有帮助我。

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 开头的数字是八进制,因此 0809 无效。

关于java - 嗨,我试图让我的 if 语句等于多个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553608/

相关文章:

java - 一行上有多个 if 语句

c - if语句中的枚举比较在c中永远不会为真

objective-c - 如果文本字段为空,则将 "informative text"添加到警报

java - 理解 list[i-1] 与 list[i]-1

Java/ Spring : "Tagging" beans in XML to get specific bean by class and tag

java - 如何为流数据创建 Flux/Publisher

java - 有没有更简单的方法来执行此 if 语句?

java - 在 Java 中为挂起的进程中断线程

java - Keycloak 使用自定义协议(protocol)映射器添加来自数据库/外部源的额外声明

JavaScript if 语句比较不起作用