为什么eclipse错误地说我的方法必须返回一个double?

Joe*_*200 0 java eclipse

对于我正在进行的计算,我制作了一个方法来计算哪个数是两个中最低的:

public static double min(double one, double two){
    if (one < two) return one; //Return one if it is less than two
    if (two < one) return two; //Return two if it is less than one
    if (one == two) return two; //Return two, because it's the same.
}
Run Code Online (Sandbox Code Playgroud)

但是,Eclipse告诉我"这个方法必须返回double类型".

我对此感到困惑,因为该方法必须返回双打!数字可以更大,更小或等于另一个数字.因此,没有返回双精度的实例.

Eclipse为什么抱怨这个?

Kis*_*kae 6

作为已经给出的答案的补充,如果其中一个双精度未定义(Double.NaN),则所有这些检查都可能失败.这是因为涉及NaN值的比较总是返回false,而不管涉及的其他值如何.

所以编译器说这个方法需要有一个默认的返回值是正确的.这可以通过此测试用例显示,该测试用例将打印"默认":

public static void main(String[] args) {
    double one = 1;
    double two = Double.NaN;
    System.out.println(min(one, two));
}

static String min(double one, double two) {
    if (one < two) return "one";
    if (one > two) return "two";
    if (one == two) return "two";
    return "defaulted";
}
Run Code Online (Sandbox Code Playgroud)