我有一个问题,在Eclipse中出现了“死代码”警告,但我真的不知道为什么。这段代码来自于我的四子棋项目,更准确地说是检查是否有人获胜的类。该方法检查所有红色水平获胜的可能性。代码如下:
/**
* 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
都没有起到任何作用,因为每个if
后面都有一个;
。这意味着你的内部for
循环在第一次迭代时始终返回 true - 这意味着column++
永远无法被执行。这就是为什么即使是简单的循环/条件语句,也应该始终使用{}
的原因。 - JonK&&
运算符。 - jhamon