0

我的战舰游戏收到“死代码”警告。我正在测试是否可以放置一艘船,并且看到如果可以放置船将面临的不同方向。

然后我使用In.class获取输入,并在检查它是否可以用布尔值放置(检查放置方向时设置为真/假)后,我使用整数的二维数组并将所有位置设置为 1(然后是起始位置+ 指定方向的长度(作为参数给出)

我的 .java 文件在这里ShipProperties.java

如果可能的话,请保持初学者技能水平的答案(基本的 i/o 和数组,我对逻辑非常好)

编辑

我把它修好了,现在它可以按预期工作了!

只需将 return 放在循环内的 if/else 中

for(int i = length; i > 0; i--)
{
 grid[startLocX][startLocY + i] = 1;
 if(i == 0)
 {
   return grid;
 }
}
4

3 回答 3

4

在您的代码中,

    for(int i = length; i > 0; i--)                               //Dead Code
    {
      grid[startLocX - i][startLocY] = 1;
      return grid;
    }

循环中的递减永远不会执行,因为在循环的第一次迭代中,您的方法会返回一个值,所以永远不要进行第二次迭代。其实你的代码是一样的:

    if(length > 0)                              
    {
      grid[startLocX - length][startLocY] = 1;
      return grid;
    }

希望能帮助到你。

于 2014-01-23T15:25:53.777 回答
1

我认为您想将 return 语句从 for 循环内部移动到if(canPlace == true)子句的末尾。我还建议您稍微整理一下代码以使其更具可读性:

if(canPlace == true)
{
    for(int i = length; i > 0; i--)                            
    { // a little less efficient perhaps (will be optimized by JIT if it's critical), but a lot more readable for sure.
        switch (ans) {
        case "Left":
            grid[startLocX - i][startLocY] = 1;
            break;
        case "Down":
            grid[startLocX][startLocY - i] = 1;
            break;
        case "Right":
            grid[startLocX + i][startLocY] = 1;
            break;
        case "Up":
            grid[startLocX][startLocY + i] = 1;
            break;
        default:
            throw new IllegalArgumentException("huh? " + ans);
        }
    }
}
// no need for an else clause since you return the grid anyway
return grid;

请注意,我正在使用字符串 switch-case(java 7 中的新功能)并检查意外参数。

于 2014-01-23T16:13:49.127 回答
1

您的循环都在第一次迭代中返回。例如

for(int i = length; i > 0; i--)
{
    grid[startLocX - i][startLocY] = 1;
    return grid;
}

int i = length
if(i > 0)
{
    grid[startLocX - i][startLocY] = 1;
    return grid;
}

所以你的循环是不必要的。实际的死代码i--永远不会被执行。

于 2014-01-23T15:25:10.457 回答