【问题标题】:conditional operator && in javajava中的条件运算符&&
【发布时间】:2017-06-14 01:40:59
【问题描述】:

我很好奇为什么只读取 while 语句中的这些条件之一。我希望 while 语句中的两个条件都为真,以便 while 循环停止。我认为 && 意味着两个条件都必须为 TRUE,但是我的程序只读取 while 语句中首先达到的任何条件,然后在没有满足其他条件的情况下终止。这个while语句我做错了什么?

do
{
    if((count%2)==0)
    {   // even
        charlestonFerry.setCurrentPort(startPort);
        charlestonFerry.setDestPort(endPort);
        FerryBoat.loadFromPort(homePort);
        charlestonFerry.moveToPort(endPort);                

    }//End if
    else
    {   // odd
        charlestonFerry.setCurrentPort(endPort);
        charlestonFerry.setDestPort(startPort);
        FerryBoat.loadFromPort(partyPort);
        charlestonFerry.moveToPort(endPort);

    }//End else
    count++;
}while(homePort.getNumWaiting() > 0 && partyPort.getNumWaiting() > 0);

【问题讨论】:

  • @RobbyCornelissen abxy 有什么关系
  • && 就是这样工作的。如果左侧结果为假,则计算机不会费心计算右侧。

标签: java conditional


【解决方案1】:

是的。 && 表示两个条件 必须 为真(如果第一个测试为假,则它会短路) - 这会产生 false。你想要||。这意味着只要任一条件为真,它就会继续循环。

while(homePort.getNumWaiting() > 0 || partyPort.getNumWaiting() > 0);

【讨论】:

    【解决方案2】:

    正如已经回答的你想使用 || 运算符,我还建议对代码结构进行一些改进。

    不要将 cmets 放入您的代码中,而是让您的代码自我记录。例如,将轮渡路线选择代码放在单独的方法setFerryRoute中。

    您可以参考docs 了解起点。

      private void setFerryRoute() {
        while (homePort.getNumWaiting() > 0 || partyPort.getNumWaiting() > 0) {
          if (isPortCountEven(count)) {
            charlestonFerry.setCurrentPort(startPort);
            charlestonFerry.setDestPort(endPort);
            FerryBoat.loadFromPort(homePort);
          } else {
            charlestonFerry.setCurrentPort(endPort);
            charlestonFerry.setDestPort(startPort);
            FerryBoat.loadFromPort(partyPort);
          }
          charlestonFerry.moveToPort(endPort);
          count++;
        }
      }
    
      // This function is not needed, I have created it just to give you
      // another example for putting contextual information in your
      // function, class and variable names.
      private boolean isPortCountEven(int portCount) {
        return (portCount % 2) == 0;
      }
    

    【讨论】:

      【解决方案3】:

      如果要在两个条件都为真时中断循环,则使用以下条件:

      while(!(homePort.getNumWaiting() > 0 && partyPort.getNumWaiting() > 0))
      

      【讨论】:

        猜你喜欢
        • 2011-08-13
        • 2014-10-19
        • 2018-03-21
        • 2015-04-06
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 2011-02-06
        • 2018-06-20
        相关资源
        最近更新 更多