2015-07-10 40 views
-8

我寫了下面的括號減少

if (((weight < 160 && (age <= 27 && age >= 22)) 
    && ((height < 72) && ((!isASmoker) && (isMale))) 
    && ((isGoodLooking) && (isAbleToRelocate)))) { 

我可以減少括號?

感謝

+8

是的,你確定可以。你有沒有嘗試過? –

+2

你只使用'&&',所以是的。基本上,您可以刪除除了外括號之外的所有內容。但是你不應該設計這樣的'if'子句。這導致不可維護的代碼。 – Turing85

+1

爲什麼首先放置所有括號? https://duckduckgo.com/?q=java+operator+precedence –

回答

3

Turing85's comment正確地指出,你實際上可以刪除所有括號,除了外部的

if (weight < 160 && age <= 27 && age >= 22 
     && height < 72 && !isASmoker && isMale 
     && isGoodLooking && isAbleToRelocate ) 

這是parethesis可以使用的最小數量。最大數量是......好吧,幾乎是無限的(有限數量,顯然,但無限的可能性)。只要您的想法正確無誤,您可以添加儘可能多的內容。

1

如果你正確地理解Java的運營商優先級,然後這可以減少到最低限度括號:

if ((weight < 160 && (age <= 27 && age >= 22)) 
&& ( height < 72 && !isASmoker && isMale) 
&& ( isGoodLooking && isAbleToRelocate)) { 

更多參考this

編輯: - 其實,如果你考慮一下,如果用「和」運營商檢查,如果第一個是真正的下一個條件ONY條件,這在邏輯上可以進一步降低至

if (weight < 160 && age <= 27 && age >= 22 
&& height < 72 && !isASmoker && isMale 
&& isGoodLooking && isAbleToRelocate) { 
+3

如果認爲它可以減少更多,因爲它只是和。只有外括號不重要? – LBes

+0

你不需要任何內括號 –

+0

謝謝,原來它甚至沒有括號,除了一個 –