[英]conditional operator && in java
我很好奇為什么在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);
是。 &&
表示兩個條件都必須為真(如果第一個測試為假,則短路)-得出false
。 您想要||
。 這意味着只要任一條件為真,它將繼續循環。
while(homePort.getNumWaiting() > 0 || partyPort.getNumWaiting() > 0);
如前所述,您想使用||。 運算符,我還建議對代碼結構進行一些改進。
不要在代碼中添加注釋,而是使代碼自記錄。 例如,將渡輪路線選擇代碼放在單獨的setFerryRoute方法中。
您可以參考文檔作為起點。
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.