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.
}
}
添加回答
舉報