简体   繁体   中英

conditional operator && in java

I am curious as to why only one of these conditions in the while statement is read. I want both conditions in the while statement to be true for the while loop to stop. 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. What am i doing wrong with this while statement?

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 . 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 .

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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