我寫了下面的括號減少
if (((weight < 160 && (age <= 27 && age >= 22))
&& ((height < 72) && ((!isASmoker) && (isMale)))
&& ((isGoodLooking) && (isAbleToRelocate)))) {
我可以減少括號?
感謝
我寫了下面的括號減少
if (((weight < 160 && (age <= 27 && age >= 22))
&& ((height < 72) && ((!isASmoker) && (isMale)))
&& ((isGoodLooking) && (isAbleToRelocate)))) {
我可以減少括號?
感謝
如Turing85's comment正確地指出,你實際上可以刪除所有括號,除了外部的
if (weight < 160 && age <= 27 && age >= 22
&& height < 72 && !isASmoker && isMale
&& isGoodLooking && isAbleToRelocate )
這是parethesis可以使用的最小數量。最大數量是......好吧,幾乎是無限的(有限數量,顯然,但無限的可能性)。只要您的想法正確無誤,您可以添加儘可能多的內容。
如果你正確地理解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) {
是的,你確定可以。你有沒有嘗試過? –
你只使用'&&',所以是的。基本上,您可以刪除除了外括號之外的所有內容。但是你不應該設計這樣的'if'子句。這導致不可維護的代碼。 – Turing85
爲什麼首先放置所有括號? https://duckduckgo.com/?q=java+operator+precedence –