2017-06-14 137 views
0

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

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

@RobbyCornelissen什么做'了'和'B'有'x'做和'y' –

+1

这就是'&&'的工作原理。如果左侧输出错误,计算机不会打扰右侧。 –

回答

2

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

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

前面已经回答了你想使用||运算符,我也会推荐一些代码结构的改进。

而不是在您的代码中放置注释,使您的代码自我记录。例如,将渡轮路线选择代码放在单独的方法中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; 
    } 
0

如果你想打破循环当两个条件都为真,则使用以下条件:

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