【问题标题】:Java "missing return statement" [closed]Java“缺少返回语句”[关闭]
【发布时间】:2016-06-10 20:55:54
【问题描述】:

这是我的代码的一小部分。问题是无论代码将进入if 语句。

public static double value(char[][] array, int x, int y) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                if (array[i][j] == (char) 120) {
                    int x_cord = i;
                    int y_cord = j;
                    int width = (x_cord - x);
                    int height = (y_cord - y);
                    Math.abs(width);
                    Math.abs(height);
                    double distance = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
                    return distance;
                }

            }
        }
    }

我知道我在某处存在逻辑缺陷,我需要以某种方式告诉程序它无论如何都会到达那里,但我可以这样做吗?

【问题讨论】:

  • 如果array 为空怎么办?在这种情况下,您需要返回一些东西。或者抛出异常。
  • 你必须从这个方法返回。现在你只在条件为真时返回。

标签: java for-loop compiler-errors return


【解决方案1】:

如果不确定,编译器不会接受返回类型为非void 的方法

  • 返回一个值或
  • 抛出异常

既然您确定循环内的return 语句总是被执行,您可以添加一个任意值的return 语句或抛出异常:

public static double value(char[][] array, int x, int y) {
    for (int i = 0; i < array.length; i++) {
        ...
    }
    throw new IllegalArgumentException("array must contain a char with code 120");
}

【讨论】:

    【解决方案2】:

    您必须在每个理论上可能的流程中都有一个return 语句,即使在运行时没有机会到达那里也是如此。只需在末尾添加一个“虚拟返回,就可以了:

    public static double value(char[][] array, int x, int y) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                if (array[i][j] == (char) 120) {
                    int x_cord = i;
                    int y_cord = j;
                    int width = (x_cord - x);
                    int height = (y_cord - y);
                    Math.abs(width);
                    Math.abs(height);
                    double distance = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
                    return distance;
                }
    
            }
        }
    
        return 0; // Or some other default
    }
    

    【讨论】:

    • 需要注意的是,通过使用这种模式,特殊含义被赋予了值 0。在这种情况下,这可能是合适的,但它会引入细微的错误,我觉得不是很哦。也就是说,鉴于手头的信息,我没有看到任何其他解决方案。
    【解决方案3】:

    尝试创建一个像这样初始化的语言环境变量double distance= 0;

     public static double value(char[][] array, int x, int y) {
         double distance= 0;
        ...
           return distance;
            }
          }
        }
       return distance;
    } 
    

    【讨论】:

      【解决方案4】:

      代码中有两个可能的路径/分支,如果您已定义方法返回值,则每个路径/分支都必须具有有效的返回语句。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 2014-03-01
        • 2014-09-22
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多