R.Strause
R.Strause

Reputation: 1

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

Upvotes: 0

Views: 74

Answers (3)

Bhanu Boppana
Bhanu Boppana

Reputation: 134

If you want break the loop when both the conditions are true, then use the following condition:

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

Upvotes: 0

Anupam Saini
Anupam Saini

Reputation: 2421

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

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

Upvotes: 2

Related Questions