简体   繁体   English

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

[英]Having trouble with recursive method in java

The compiler says I'm not returning an integer. 编译器说我不返回整数。 The getC method returns an integer. getC方法返回一个整数。 How can I fix this? 我怎样才能解决这个问题?

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

This problem arises when your method doesn't return a result by following all the paths. 当您的方法没有遵循所有路径返回结果时,就会出现此问题。 In this case, if the if inside the for loop never gets executed, you aren't returning anything. 在这种情况下,如果for循环内的if永远不会执行,则您将不会返回任何内容。

Just add a default return statement at the bottom of your method: 只需在方法底部添加一个默认的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
}

Simply add default value in the end 只需在最后添加默认值

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 
}

OR you can throw an Exception such as IllegalArgumentException in case of invalid value. 或者,如果值无效, 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();
} 

You're not returning an integer in every case . 您并非在每种情况下都返回整数。 If the inner condition is never met, control will flow to the end of the method without anything being returned. 如果内部条件从不满足,则控制将流至方法的结尾,而不会返回任何内容。

You need to add a 'return' for the case when your 'for' loop terminates - ie with i==0. 对于“ for”循环终止的情况,您需要添加“ return”,即i == 0。 Not knowing what this code is doing, it's entirely possible that you are certain the the inner return must occur for some value of i, but neither I nor your compiler can determine that this is the case, merely by looking at this code fragment. 不知道这段代码在做什么,完全有可能确定对于i的某个值必须发生内部返回,但是仅通过查看此代码片段,I或您的编译器都无法确定是否是这种情况。 Modern compilers are pretty smart, but not that smart ;-) 现代编译器很聪明,但并不那么聪明;-)

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

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