在下面的代码中,我希望不必在最后一个 else 块中初始化变量a
,b
但是编译器不喜欢它。
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
我原以为编译器可以进行静态分析以找出如果设置为 falsek
将不会被评估。c
所以我的问题是为什么编译器要求我初始化a
和b
?