【问题标题】:How to ask multiple conditions to return true Java如何要求多个条件返回 true J​​ava
【发布时间】:2017-02-23 18:21:44
【问题描述】:

我正在编写一个必须满足前提条件的代码,如果条件都满足,那么它将返回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;
}

【问题讨论】:

  • 如果多个条件都必须为真,则在条件之间使用 && 运算符。

标签: java preconditions


【解决方案1】:

检查失败时返回 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;
}

【讨论】:

  • 我想我的错误与原始代码兼容。 :-) 我修好了。
  • 哎呀,当我阅读他的代码时,我只看到'day>0'。一定是刷得太快了。忽略我之前的评论。虽然我不确定改变是否有效。我想你想要 `(day
【解决方案2】:

在代码顶部添加一个布尔变量:

bool legit = true;

在每个if 语句中,如果条件为假,则更改合法值。如果值为 true,则不要更改它。

条件结束,返回变量:

return legit;

如果任何检查不合法,该方法将返回 false。

编辑:Espen 的解决方案更有效(如果稍微不那么准确 - 请参阅评论),尽管我会 OR 退出双重条款:

 if((mon < 1) || (mon>12)) return false;

if((day < 1) || (day > 31)) return false; 

但是请注意,这仍然可以将无效日期返回为有效日期,例如:6 月 31 日

【讨论】:

  • 另一种解决方案可能更有效,但我不明白为什么人们对你的答案投了反对票,这是对的。
【解决方案3】:

您可以使用JodaTime API

 public static boolean isLegitmate(int mon, int day, int year){
    try {
        new DateTime().withMonthOfYear(mon).withYear(year).withDayOfMonth(day);
        return true;
    } catch (Exception e){
        return false;
    }
}

【讨论】:

    【解决方案4】:

    试试这个:

    public static boolean isLegitimate(int mon, int day, int year){
    
    if(  (mon >= 1 && mon <= 12) && (year > 0) && (day >=0 && day <=31)){
       if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0))
        if (day >29)
            return false;
        return true;
    }
    }
    

    【讨论】:

      【解决方案5】:

      这会将您的逻辑分解为多种方法。我稍微修改了闰年的逻辑。

      public class MultipleConditions {
      
          public static boolean isLegitimate(int mon, int day, int year) {
      
      
              return validMonth(mon) && validYear(year) && validDay(day) && validFebDay(mon, day, year);
          }
      
          private static boolean validFebDay(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.
              if (mon!=2)
                  return true; // Not in feb
              if (year%4 != 0)
                  return day <= 28; // Not a leap year
      
              if (year%100 == 0) {
                  return day <= 29; // Divisible by 4, but not a centurial year
              }
              // Divisible by 4, centurial year, and divisible by 400
              if (year%400==0) {
                  return day <=29;
              }
              // Divisible by 4, centurial year not divisible by 400
              return day <= 28;
          }
      
          private static boolean validDay(int day) {
              // checks to see if the days are between 1 and 31
              return day >= 0 && day <= 31;
          }
      
          private static boolean validYear(int year) {
              return year > 0;
          }
      
          private static boolean validMonth(int mon) {
              // checks to see if the months are between 1 and 12
              return (mon >= 1) && (mon <= 12);
          }
          public static void main(String args []) {
              System.out.println(isLegitimate(2, 23, 2017));
              System.out.println(isLegitimate(2,29,2017));
              System.out.println(isLegitimate(3,31,2017));
          }
      }
      

      【讨论】:

        【解决方案6】:

        只是另一个建议。

        对于这种特定情况,它可能看起来不太好,但可以帮助有类似问题的人(“要求多个条件返回真”)。

        public static boolean isLegitimate(int mon, int day, int year){
            return Stream.of(
                    checkMonth(mon),
                    checkYear(year),
                    checkDay(day),
                    checkFebruary(mon, day, year))
            .allMatch(check -> check);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-16
          • 1970-01-01
          • 1970-01-01
          • 2022-12-11
          • 1970-01-01
          相关资源
          最近更新 更多