2014-02-25 39 views
0

我有一個對象數組。我想掃描它,只要我找到的對象不是null,就增加一個計數器。當我找到第一個空對象時,我想要跳出for循環,因爲沒有理由繼續循環。Java中的死代碼錯誤

我寫了下面的代碼:

// counter variable initialized to zero 
int counter = 0; 

// scan the array 
for(int i = 0; i < this.array.length; i++) { 

    // as long as the object found is not null 
    while(!this.array[i].equals(null)) { 

     // increase the value of the counter by 1 
     counter += 1; 

    } 

    // when the first null object found, jump out of the loop 
    break; 

} 

第i ++在for循環中被標記和警告是死代碼。但是,我想這是有道理的,因爲當我找到第一個空對象時,我停止循環。所以沒什麼好擔心的,或者...?

+3

你是一個迭代後打破你的循環。所以你永遠不會去增加聲明。 –

+0

你的while循環不應該是一個循環......它應該是一個if語句 – Gus

回答

5

您無條件地for循環的第一次迭代結束時跳出for循環。這與「找到第一個空對象時無關」 - 它只是在循環體的末尾。

此外,您while循環永遠不會結束,除非array[i]真的是空(在這種情況下,它會拋出一個NullPointerException)。我想你想:

for (int i = 0; i < this.array.length; i++) { 
    if (array[i] != null) { 
     counter++; 
    } else { 
     break; 
    }  
} 

或者更好,使用迭代器:

int counter = 0; 
for (String item : array) { // Or whatever the type should be 
    if (item != null) { 
     counter++; 
    } else { 
     break; 
    } 
} 
+0

Oooops!我想用if語句而不是一段時間,這總是讓我困惑!謝謝! – PeterHiggs

0

更改,而迭代if條件,因爲一旦當條件爲真也不會斷裂,去無限循環。爲了滿足您的要求,請使用下面的代碼

if(this.array[i] != null) { 
    // increase the value of the counter by 1 
    counter += 1; 
} 
else { 
    break; 
} 
+0

@ZouZou哦,是的,我已經更新了answer.Thnks – Kick

0

這個最簡單的解決辦法是:

int counter = 0; 
for (Object item : array) { 
    if (item == null) { 
    break; 
    } 
    ++counter; 
}