2017-09-06 78 views
1

我不知道下面的代碼如何返回false。Java邏輯短路運算符如何工作

String line =""; 
if (line.length() > 0 && !line.startsWith("/*") || !line.startsWith("--")) {  
    return false; 
} 

我知道,如果我們使用& &是,執行從左側開始和它進行唯一如果離開結果爲真,否則不要繼續。

但在上面的代碼中它返回false。 line.length()的值爲0,但其驗證的第二個條件並評估爲真,因爲其他兩個條件爲真並返回false。

幫我理解這個操作符。

謝謝。

回答

3

您有兩個操作員。 AND運算符首先被評估並返回false。然後,OR運算符求值並返回true,因爲或操作者的第二個操作數爲真:

if (line.length() > 0 && !line.startsWith("/*") || !line.startsWith("--")) 
      false  &&  not evaluated 
        false      ||   true 
               true  

如果你想的AND運算符的第二個操作數,包括OR操作符,你應該加上括號:

if (line.length() > 0 && (!line.startsWith("/*") || !line.startsWith("--"))) 
     false        not evaluated 
        false 
+0

謝謝你的時間。我所說的是,如果**** line.length()> 0 ****失敗,爲什麼它會驗證其他事情。它應該短路嗎?它不應該驗證其他條件,它應該通過if測試。糾正我,如果我錯了。 – Abdul

+0

@Abdul它確實短路,這就是爲什麼'!line.startsWith(「/ *」)'永遠不會被評估的原因,然而'' !line.startsWith(「 - 」)不是AND運算符的操作數的一部分,因此在AND運算符評估爲false之後,OR將被評估 - '(false ||!line.startsWith(「 - 「 - 」)' - returned true。 – Eran

+0

謝謝,在添加括號後,我明白了。 – Abdul

0

如果向代碼中添加括號,它將更清晰,例如,

if ((line.length() > 0 && !line.startsWith("/*")) || !line.startsWith("--")) 

第一操作者&&而第二運營商||被評估爲真進行評估,以括號內假。

+0

我知道,我對Java Short電路運算符感到困惑。 – Abdul

+0

@Abdul這裏沒有短路。 。左邊的運算符將返回'false'或'true',並將該值與'||'的右邊進行比較。如果你想短路它,你必須在聲明中使用括號 –

0

首先,line.length() > 0 && !line.startsWith("/*")false。然後,評估繼續到false || !line.startsWith("--")true。這就是爲什麼if語句塊中的代碼被執行的原因。

從我的推斷,我認爲你真正需要的是:

if (line.length() > 0 && (!line.startsWith("/*") || !line.startsWith("--"))) 

也就是在括號中的電源炫耀!