3 回答
TA贡献1836条经验 获得超4个赞
问题是编译器不知道当你访问它时x 会被初始化。那是因为编译器不会检查循环体是否真的会被执行(在极少数情况下,即使是这样一个简单的循环也可能不会运行)。
如果条件不总是正确的,那么你的 if-block 也是如此,即如果你使用这样的布尔变量:
int x;
boolean cond = true;
if( cond ) {
x = 5;
}
//The compiler will complain here as well, as it is not guaranteed that "x = 5" will run
System.out.println(x);
你作为一个人会说“但cond被初始化true并且永远不会改变”但编译器不确定(例如,因为可能的线程问题),因此它会抱怨。如果你创建cond一个 final 变量,那么编译器会知道cond在初始化后不允许更改,因此编译器可以内联代码以if(true)再次有效地拥有。
TA贡献2012条经验 获得超12个赞
如果您将 if 块中的条件从trueto更改为,false您将得到与variable 'x' might not have been initialized. 当你这样做时if(true),编译器可以理解 if 块中的代码将始终运行,因此变量 x 将始终被初始化。
但是当您在 for 循环中初始化变量时,可能会发生 for 循环永远不会运行并且变量未初始化的情况。
public static void main(String[] args) {
int x; // Declared in main method
if(false)
{
x=5; //compile error
for(int i=0;i<5;i++)
{
//x=5 initialized inside loop
}
}
System.out.println(x);
}
为避免这种情况,将变量初始化为 int x = 0;
TA贡献1880条经验 获得超4个赞
它仍然可以访问,但程序可能永远不会访问 for 块。由于编译器不满足 for 循环之外的任何其他 var 初始化,它会给你一个错误。为了编译它,您必须使用默认值初始化变量:
class Myclass {
public static void main (String[] args) {
int x = 0; // Declared in main method and init with a default value.
if(true) {
for(int i=0;i<5;i++) {
x=5;// Reinitialized inside loop
}
}
System.out.println(x); // No problems here.
}
}
添加回答
举报