繁体   English   中英

在Java中使用递归方法遇到麻烦

[英]Having trouble with recursive method in java

编译器说我不返回整数。 getC方法返回一个整数。 我怎样才能解决这个问题?

public static int calcCost(Guard[] g, int spot){
    if(spot >= 31078657) return 0;
    else {
        for(int i = 51499; i >= 0; i--){
            if(g[i].getS() == spot && g[i].getF() <= 31078657) {
                return (g[i].getC() + calcCost(g, g[i].getF() + 1));
            }
        }
    }
}

当您的方法没有遵循所有路径返回结果时,就会出现此问题。 在这种情况下,如果for循环内的if永远不会执行,则您将不会返回任何内容。

只需在方法底部添加一个默认的return语句:

public static int calcCost(Guard[] g, int spot){
    if(spot >= 31078657) return 0;
    else {
        for(int i = 51499; i >= 0; i--){
            if(g[i].getS() == spot && g[i].getF() <= 31078657) {
                return (g[i].getC() + calcCost(g, g[i].getF() + 1));
            }
        }
    }
    //here
    return 0; //or another desired default value
}

只需在最后添加默认值

public static int calcCost(Guard[] g, int spot){
    if(spot >= 31078657) return 0;
    else {
        for(int i = 51499; i >= 0; i--){
            if(g[i].getS() == spot && g[i].getF() <= 31078657) {
                return (g[i].getC() + calcCost(g, g[i].getF() + 1));
            }
        }
    }
    return -1;// add default value here 
}

或者,如果值无效, IllegalArgumentException可以引发诸如IllegalArgumentException的异常。

public static int calcCost(Guard[] g, int spot){
    if(spot >= 31078657) return 0;
    else {
        for(int i = 51499; i >= 0; i--){
            if(g[i].getS() == spot && g[i].getF() <= 31078657) {
                return (g[i].getC() + calcCost(g, g[i].getF() + 1));
            }
        }
    }
    throw new IllegalArgumentException();
} 

您并非在每种情况下都返回整数。 如果内部条件从不满足,则控制将流至方法的结尾,而不会返回任何内容。

对于“ for”循环终止的情况,您需要添加“ return”,即i == 0。 不知道这段代码在做什么,完全有可能确定对于i的某个值必须发生内部返回,但是仅通过查看此代码片段,I或您的编译器都无法确定是否是这种情况。 现代编译器很聪明,但并不那么聪明;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM