我有一個對象數組。我想掃描它,只要我找到的對象不是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循環中被標記和警告是死代碼。但是,我想這是有道理的,因爲當我找到第一個空對象時,我停止循環。所以沒什麼好擔心的,或者...?
你是一個迭代後打破你的循環。所以你永遠不會去增加聲明。 –
你的while循環不應該是一個循環......它應該是一個if語句 – Gus