我遇到了一個問題,我在Eclipse中遇到了「死代碼」警告,我真的不知道爲什麼。代碼來自我的Connect Four項目,更確切地說,它是從Class中檢查是否有人獲勝。該方法檢查所有水平獲勝可能性爲紅色。代碼如下:死碼從哪裏來?
/**
* Method to check the horizontal winning possibilities for red
* @return true if red won or false if not
*/
public boolean checkHorRed(){
for(int line = 0; line < 6; line++) {
for(int column = 0; column < 4; column++) { //column++ is underlined and causes the "dead Code" warning
if(gw.buttons[line][column].getIcon().equals(gw.red));
if(gw.buttons[line][column+1].getIcon().equals(gw.red));
if(gw.buttons[line][column+2].getIcon().equals(gw.red));
if(gw.buttons[line][column+3].getIcon().equals(gw.red));
return true;
}
}
return false;
}
這個遊戲甚至因爲這個方法而立即獲勝。奇怪的是,類中所有其他方法看起來幾乎一樣,不會導致任何問題。以下是檢查黃色垂直獲勝可能性的方法,以進行比較:
/**
* Method to check the vertical winning possibilities for yellow
* @return true or false
*/
public boolean checkVertYel(){
for(int line = 3; line < 6; line++) {
for(int column = 0; column < 7; column++) {
if(gw.buttons[line][column].getIcon().equals(gw.yellow))
if(gw.buttons[line-1][column].getIcon().equals(gw.yellow))
if(gw.buttons[line-2][column].getIcon().equals(gw.yellow))
if(gw.buttons[line-3][column].getIcon().equals(gw.yellow))
return true;
}
}
return false;
}
這一個不會引起任何問題。有人可以告訴我警告來自哪裏嗎?如果您需要更多信息,請告訴我。
因爲它代表所有那些'if's的沒有做任何事情,因爲你已經有了一個','各一個。這意味着你的內部'for'循環**總是**在第一次迭代時返回true,意味着'列++'永遠不會到達。這就是爲什麼你應該總是使用'{}',即使使用簡單的循環/ ifs。 – JonK 2014-10-30 09:07:34
你應該考慮在你的if語句中使用'&&'操作符。 – jhamon 2014-10-30 09:09:32