我遇到了一个问题,我在 Eclipse 中收到“死代码”警告,我真的不知道为什么。代码来 self 的 Connect Four 项目,更准确地说,它来自检查是否有人获胜的类。此方法检查红色的所有水平获胜可能性。代码如下:
/**
* 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;
}
这个不会造成任何问题。有人可以告诉我警告来自哪里吗?如果您需要更多信息,请告诉我。
最佳答案
你函数中的死代码是the increment statement您的内部 for 循环(column++
)。 return true
语句将始终执行(如果执行了循环),因此永远不会发生循环增量。
这是您的代码,但格式正确:
// ...
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 true
会一直执行,所以内层循环的increment语句不会执行。
你的代码应该是这样的:
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)
&& gw.buttons[line][column+1].getIcon().equals(gw.red)
&& gw.buttons[line][column+2].getIcon().equals(gw.red)
&& gw.buttons[line][column+3].getIcon().equals(gw.red) {
return true;
}
}
}
return false;
}
关于java - 死代码从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648836/