【问题标题】:Valid date method logic?有效的日期方法逻辑?
【发布时间】:2016-02-22 14:23:39
【问题描述】:

我无法理解为什么此方法会使我输入的所有日期都返回为真(有效)。这种方法中唯一可以完美运行的部分是闰年声明。我尝试定义另一个名为 isValid 的变量并将其返回为 true 并添加一个 if 语句以将该方法返回为 true 或 false,但是,这只适用于某些日期,我也不太明白。谁能告诉我为什么这种方法有缺陷?

public boolean isValid()
{
  if ( month == Month.JAN || month == Month.MAR || 
        month == Month.MAY || month == Month.JUL
        || month == Month.OCT || month == Month.OCT 
        || month == Month.DEC && day <= Month.DAYS_ODD )
     return true;
  if ( month == Month.APR || month == Month.JUN 
        || month == Month.SEP
        || month == Month.NOV && day <= Month.DAYS_EVEN )
     return true;
  boolean leapYear = false;
  if ( year % Month.QUADRENNIAL == 0 || year % Month.CENTENNIAL == 0
        || year % Month.QUATERCENTENNIAL == 0 )
     leapYear = true;
  if ( leapYear )
     if ( month == Month.FEB && day <= Month.DAYS_FEB + 1)
        return true;
  if ( month == Month.FEB && day <= Month.DAYS_FEB )
     return true;
  return false;

}

public class Month 
{
   public static final int JAN = 1;
   public static final int FEB = 2;
   public static final int MAR = 3;
   public static final int APR = 4;
   public static final int MAY = 5;
   public static final int JUN = 6;
   public static final int JUL = 7;
   public static final int AUG = 8;
   public static final int SEP = 9;
   public static final int OCT = 10;
   public static final int NOV = 11;
   public static final int DEC = 12;
   public static final int DAYS_ODD = 31;
   public static final int DAYS_EVEN = 30;
   public static final int DAYS_FEB = 28;
   public static final int QUADRENNIAL = 4;
   public static final int CENTENNIAL = 100;
   public static final int QUATERCENTENNIAL = 400;
}

【问题讨论】:

  • 逻辑全错。如果月份有效,则跳过以下所有检查。事实上,如果 any 日期的单个组件有效,则该方法将返回 true,即使所有其他组件都无效。
  • 您需要在OR 部分周围使用括号。
  • @JimGarrison 如果我错了,请纠正我,但我认为我的第一个 if 语句背后的逻辑是“如果月份是一月,或者月份是三月,或者月份是五月……并且有 31 天或更少的天,然后返回 true。那么它们不是必须是 2 个真正的组件吗?
  • @PM77-1 为什么?这如何改变代码?

标签: java logic


【解决方案1】:

闰年的逻辑是错误的。它应该如下所示。

if ( year % Month.QUADRENNIAL == 0
    || year % Month.QUATERCENTENNIAL == 0 )
 leapYear = true;

能被100整除的数字不是闰年,例如:1900,它不是闰年。

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多