【问题标题】:Is there a || operator for int?有没有|| int 的运算符?
【发布时间】:2016-01-03 19:45:41
【问题描述】:

我正在尝试编写一个方法,该方法采用单个 int 参数,该参数是数字月份并返回给定月份的天数。因此,参数 1 将返回 31,因为 1 月份有 31 天,而参数 2 将返回 28,因为 2 月份有 28 天。

这是我目前所拥有的:

 public static void daysInMonth(int month) {
           if (month == 1||3||5||7||8||10||12)
         System.out.println("31");
      else if (month == 4||6||9||11)
         System.out.println("30");
      else if (month == 2)
         System.out.println("28");

我不断收到错误消息“运算符 || 不能应用于布尔值,整数。”谁能帮我弄清楚该怎么做?

【问题讨论】:

  • 您是在寻找按位运算符还是在寻找月份==1 ||月==2
  • 提示中明确指出,实现应该使用逻辑操作(&& 或 ||),而不是使用十二个 if / else if / else 块。
  • Isiaiah,我使用了你的第二个选项,我不再在静态方法中收到错误消息,但是当我尝试在 main 方法中调用静态方法时,我收到错误消息“此处不允许使用 'void' 类型。”
  • 返回类型不是 void。你的代码有问题。
  • 让我补充一下我的问题,你介意看一下吗?

标签: java int boolean operators


【解决方案1】:

您可以通过使用java.time.Month 的新 Java 1.8 时间 API 避免任何 switch 或 if/else 语句:

public static int daysInMonth(int month) {
    return Month.of(month).minLength();
}

【讨论】:

  • voidreturn ?您可能正在寻找maxLength(),它如何处理(闰)年?
  • @JigarJoshi 哎呀,从问题中的代码复制和粘贴错误,谢谢。我使用了minLength(),因为该示例明确指出二月应该是 28 天。如果要考虑闰年,length(boolean leapYear) 会是更好的选择
【解决方案2】:

你想要这样的东西:

if ( (month == 1) || (month == 3) || (month == 5) || (month == 7)
                  || (month ==  8) || (month == 10)

【讨论】:

    【解决方案3】:

    || 将导致boolean 然后boolean || int 无效操作

    你需要的是

    month == 1 || month == 3 || ...
    

    Map<Integer, Integer> monthNumberToMaxDaysMap

    这样你也没有覆盖闰年的场景,它适合重复使用已经解决的问题

     public static void daysInMonth(int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month -1);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH)
     }
    

    上述方法只考虑当年,你也可以利用它来过年

    【讨论】:

      【解决方案4】:

      您可以使用 ||布尔表达式上的运算符:

      if (month == 1 || month == 3 || month == 5) {
          // do something ...
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-04
        • 2020-12-13
        • 2012-07-11
        • 2012-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多