當然Varun的回答是正確的。另外,我想詳細說明一些意見,並展示解決問題的另一種方法,該方法更簡單,不太可能包含錯誤。
在閱讀問題的陳述,你可能會注意到,該方法返回一個值,如果滿足一定條件,或返回0
其他。因此,您可以使用默認值0
初始化結果,如果條件滿足,則更改結果,然後返回結果。這將減少代碼:
public int max1020(int a, int b) {
int result = 0;
if (a >= 10 && a <= 20) result = a;
if (b >= 10 && b <= 20 && b > result) result = b;
return result;
}
不能讓它更簡單,我想。 (但是,如果可以的話,請評論,我愛KISS!:))
該解決方案產生略有不同的結果,如果兩個a
和b
在範圍和a=b
,它將返回a
。如果這種情況發生,問題陳述並不是很清楚,Varun的回答也表明了這一點。巧合(或不)Codingbat不檢查這種情況。在這種情況下,網站上提出的解決方案也會返回a
。
如果你認爲它應該返回0
時a=b
,它很容易調整,
public int max1020(int a, int b) {
int result = 0;
if (a != b) {
if (a >= 10 && a <= 20) result = a;
if (b >= 10 && b <= 20 && b > result) result = b;
}
return result;
}
還是蠻簡單的:)
爲了解釋TJCrowder的約壓痕評論:如果你把身體的if
聲明在下一行,你應該使用大括號和縮進行。否則,很容易誤讀它,或者在更改代碼時出錯。
// this can be error prone and harder to read,
// especially if you have multiple if statements,
// or add a statement to the body of the if statement in the future
// (shouldn't do this)
if (condition)
statement;
// Personally I think this is totally fine for a simple statement.
// But I know not everybody will agree
if (condition) statement;
// Usually, you'll see this formatting.
// Even without reading anything, the formatting makes it instantly clear
// which statements belong to the body of the if
if (condition) {
statement;
}
邊注:在代碼中else
聲明屬於只最後if
。你的格式可以通過在這些之間不加空格來表示清楚,例如
if (condition) statement;
else statement;
if (condition) {
statement;
} else {
statement;
}
在代碼中else
聲明實際上是過時的,你可以簡單地return 0;
在最後一行。
Varun建議您可以使用else if
s是正確的。理論上,如果第一個if
聲明的條件爲真,則使用else if
將使代碼跳過其他if
的測試,並且效率更高一些。此外,它會顯示只有在前面的if
語句錯誤時纔會達到後續的if
語句。
然而,實際上,在你的代碼中,它並不重要,因爲如果條件爲true
,並且後續的if
語句永遠無法到達,則該方法將完成並返回一個值。
對不起,它的Java! –
爲什麼不簡化代碼,只需檢查'a'是否在第一個範圍內?與'b'同上然後找到最大的 –
'&&'與'||'具有相同的優先級,因此您的if子句從左到右讀取。你需要圍繞「內部」子句使用括號。 – Evert