我正在寫一個簡單的GCD函數,我相信它會一直返回一些東西,因爲我在if中寫了一個return語句。如何確保程序不會以編譯錯誤結束。最後寫另一個return語句可以嗎?如何確保你在遞歸函數中返回一些東西?
private static int gcd(long a, long b){
if(b==0)
return (int)a;
else{
a=a%b;
gcd(b,a);
}
//I want to avoid the next statement as I think it is redundant,
//but the compiler does not allow me to skip it.
return 0;
}
如果正常執行意味着它不應該達到最終返回語句,那麼您可以並且應該拋出異常。 – Michael
有一個@CheckReturnValue註釋,[Google的errorprone](http://errorprone.info/bugpattern/CheckReturnValue)用來確保您使用返回值。 –
@AndyTurner根本不是他要求的 – Michael