有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带数组的java死代码?

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

然后,我使用In.class获取输入,在检查是否可以使用布尔值放置输入(检查放置方向时设置为true/false)后,我使用int的2D数组,并将所有位置设置为1(开始位置然后+指定方向上的长度(作为参数给定))

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

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

编辑

我把它修好了,现在它可以正常工作了

只需将返回放入循环中的if/else

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

共 (3) 个答案

  1. # 1 楼答案

    在你的代码中

        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;
        }
    

    希望有帮助

  2. # 2 楼答案

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

    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 ,永远不会执行

  3. # 3 楼答案

    我认为您希望将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;
    

    请注意,我使用的是字符串开关大小写(Java7中新增)并检查是否有意外参数