【问题标题】:Using multiple operators in a while statement在 while 语句中使用多个运算符
【发布时间】:2013-12-28 17:25:26
【问题描述】:

您好,我正在尝试同时使用 && 和 || while 语句中的运算符。我想我可以通过使用另一个“while”来做到这一点,但我想知道是否有任何方法可以通过将它们一起使用来做到这一点。

while (month2<month1 && month2<1 || month2>12 ){
    System.out.println("Enter the return month (1-12) : ");
    month2 = input.nextInt();
    }

这是我遇到问题的部分。即使它小于提货月份,它也不会再次提示用户返回月份。

【问题讨论】:

  • 有什么问题?多次检查不要做2 while,这样是正确的。

标签: java operators conditional-statements


【解决方案1】:

也许你的意思是:

while (month2 < month1 && (month2 < 1 || month2 > 12))

month2 &lt; 1month2 &gt; 12 之一为真时,它表示迭代;当month2 &lt; month1.

您所写内容的隐含操作顺序是:

(month2 < month1 && month2 < 1) || month2 > 12

使用括号明确将允许您检查正确的条件。

【讨论】:

    【解决方案2】:

    你们很亲密。

    while ((month2<1 || month2>12) && month2<month1){
      System.out.println("Enter the return month (1-12) : ");
      month2 = input.nextInt();
    }
    

    【讨论】:

      【解决方案3】:

      看起来你只需要另一组括号:

      while (month2 < month1 && (month2 < 1 || month2 > 12))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-03
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2013-07-30
        • 2013-04-30
        相关资源
        最近更新 更多