3
在下面的代碼我期望它應該不需要初始化變量a
和b
在最後else塊,但是編譯器不喜歡它。流量分析 - 變量可能尚未初始化
import java.util.Random;
public class Foo {
private void foo() {
double a,b;
boolean c;
double r = (new Random()).nextDouble();
if(r < 0.25) {
a = 1;
b = 2;
c = true;
} else if(r >= 0.25 && r < 0.75) {
a = 3;
b = 3;
c = true;
} else {
// why is it necessary to init a and b here?
// given that c is set to false
c = false;
}
if(c) {
double k = a + b;
}
}
}
用上述代碼時,編譯器確實抱怨。
bash-3.2$ javac Foo.java
Foo.java:25: variable a might not have been initialized
double k = a + b;
^
Foo.java:25: variable b might not have been initialized
double k = a + b;
^
2 errors
我本來以爲編譯器可以做靜態分析,以弄清楚,如果c
設置爲false k
將不進行評估。所以我的問題是爲什麼編譯器要求我初始化a
和b
?