简体   繁体   English

Java中的条件运算符&&

[英]conditional operator && in java

I am curious as to why only one of these conditions in the while statement is read. 我很好奇为什么在while语句中只读取其中一个条件。 I want both conditions in the while statement to be true for the while loop to stop. 我希望while语句中的两个条件都成立,以使while循环停止。 I thought && meant that both conditions must be TRUE, but my program reads only whichever condition in the while statement that is reached first, then terminates without the other condition having been met. 我以为&&表示两个条件都必须为TRUE,但是我的程序仅读取在先到达的while语句中的任何条件,然后在不满足其他条件的情况下终止。 What am i doing wrong with this while statement? 我在使用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);

Yes. 是。 && means both conditions must be true (and it short circuits if the first test is false) - which yields false . &&表示两个条件都必须为真(如果第一个测试为假,则短路)-得出false You wanted || 您想要|| . Which means as long as either condition is true it will continue looping. 这意味着只要任一条件为真,它将继续循环。

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

As already answered you want to use || 如前所述,您想使用||。 operator, I would also recommend some improvements in the code structure. 运算符,我还建议对代码结构进行一些改进。

Instead of putting comments in your code, Make your code self documenting. 不要在代码中添加注释,而是使代码自记录。 For example, put the ferry route selection code in a separate method setFerryRoute . 例如,将渡轮路线选择代码放在单独的setFerryRoute方法中。

You can refer to docs for a starting point. 您可以参考文档作为起点。

  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;
  }

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM