编程语言
首页 > 编程语言> > 如何要求多个条件返回真正的Java

如何要求多个条件返回真正的Java

作者:互联网

我正在编写一个必须符合前提条件的代码,如果条件都满足,那么它将返回true.我尝试过多个“if”语句,但这似乎不起作用.嵌套if语句似乎不是这里的答案,我不认为“else if”语句可行.我要问的是,这样做的正确方法是什么?我写if语句错了吗?

继承我的代码:

public static boolean isLegitimate(int mon, int day, int year){

    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.


    // TODO 1: Check if a date is valid.

    //checks to see if the months are between 1 and 12
    if((mon >= 1) && (mon <= 12)) {

    }
    //checks to see if the years are greater than 1
    if (year > 0){

    }
    //checks to see if the days are between 1 and 31
    if ((day >=0) && (day <=31)){

    }

    //This checks that if the month is February, is divisible by 4 evenly,
    //and is divisible by 100 evenly, then the days can not exceed 29
    if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){
        if (day >29){
            return false;
        }
    }

    return true;
}

解决方法:

检查失败时返回false.
如果其中一个先决条件失败,则无需进一步检查.

public static boolean isLegitimate(int mon, int day, int year){

    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.

    // TODO 1: Check if a date is valid.

    //checks to see if the months are between 1 and 12
    if(mon<1) return false;
    if(mon>12) return false;

    //checks to see if the years are greater than 1
    if(year<=0) return false;

    //checks to see if the days are between 1 and 31
    if(day<=0) return false;
    if(day>31) return false;

    //This checks that if the month is February, is divisible by 4 evenly,
    //and is divisible by 100 evenly, then the days can not exceed 29
    if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){
        if (day >29){
            return false;
        }
    }
    return true;
}

标签:java,preconditions
来源: https://codeday.me/bug/20190823/1701229.html