java - 如何要求多个条件返回 true J​​ava

标签 java preconditions

我正在编写一个必须满足先决条件的代码,如果所有条件都满足,那么它将返回 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 - 如何要求多个条件返回 true J​​ava,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423372/

相关文章:

java - 将 "<"或 ">"作为参数传递给比较器

java - 公共(public)方法中的前置条件和后置条件检查

grails 变更日志先决条件不执行任何操作

java - 将 3D 点投影到 2D 点

java - 在其他语言中,我可以对整数进行 boolean 测试。在Java中,我可以说像:这样的东西吗?

java - 在每次出现另一个修复字符时插入一个修复字符

java - 带有先决条件的轻量级 Java 库?

semantics - 公理语义 - 如何计算最弱的前提条件

c# - C#:如何在使用“默认”存储时向属性添加前提条件?

java - 类和接口(interface)的初始化