从递归方法返回值

时间:2016-11-23 13:01:19

标签: java recursion return-value

我有一个递归方法,我希望从特定if语句返回true时返回一个值(它总是这样做)

    if (compactArray != null) {
            if (arrayCount == (compactArray[0].length - 1)) {
                return compactArray;//i want to return here
            }
        }

但Java不会让我从if返回,并抛出一个警告,我需要添加一个返回值。

一个人做什么?完整方法如下

public String[][] diXmlRecursiveRead(Iterator<Element> list, String[] columnNames, String[][] compactArray,
        Integer arrayCount) {
    Element element = null;
    String[] columns = null;

    while (list.hasNext()) {
        element = list.next();

        // Assign data to the two dimensional array, starting from position
        // 1 in the length to not overwrite the column names.
        // This is also where i would print the column name plus its
        // attribute value if i was printing to console.
        if (columnNames != null) {
            for (int a = 0; a < columnNames.length; a++) {
                compactArray[a][arrayCount] = element.getAttributeValue(columnNames[a]);
            }
        }

        // Find the element that contains the columns="" information
        if (element.getAttributeValue("columns") != null) {
            // reset the array count, since we are processing a new
            // columns="" section
            arrayCount = 1;

            columns = element.getAttributeValue("columns").toString().split(",");

            // set width size +1 to make room for the column names
            // (columnNames + data +1)
            compactArray = new String[columns.length][element.getChildren().size() + 1];

            // Set the EVE column names in the first column of the two
            // dimensional array
            for (int a = 0; a < columns.length; a++) {
                compactArray[a][0] = columns[a];
            }
        }

        // After added the last value to the two dimensional array return the
        // array[][]
        if (compactArray != null) {
            if (arrayCount == (compactArray[0].length - 1)) {
                return compactArray;//i want to return here and not at the end!
            }
        }

        // Method calls itself with a new level of the child
        diXmlRecursiveRead(element.getChildren().iterator(), columns, compactArray, arrayCount++);
    }
    //Java want me to return here!!
}

5 个答案:

答案 0 :(得分:3)

看一下这个例子:

static int count = 0;
private static boolean foo() {
    if (count == 5) {
        return true;
    }
    count ++;
    return foo();
}

请注意,使用'return'语句调用递归调用。
考虑执行递归方法时正在构建的堆栈。在某些时候,所有方法都需要开始在堆栈中返回一个值。

答案 1 :(得分:1)

您需要传递String [] [] compactArray参数并返回该参数。这是您的方法将在最后返回的结果。

当最深层次的递归完成时,返回开始。然后一切都会通过,直到第一次调用你的方法。

添加了一些代码:

    package recursion;

import java.util.Iterator;
import java.util.LinkedList;

import javax.xml.bind.Element;

class Recursionat0r {

    static private int threshhold = 3;

    public static void main(String[] grmlZ) {

        Recursionat0r recursionat0r = new Recursionat0r();

        String[] columnNames = { "hello", "world" };

        String[][] compactArray = new String[4][10]; // would recommend
                                                        // ArrayList here

        compactArray = recursionat0r.diXmlRecursiveRead(null, columnNames, compactArray, 0);

        recursionat0r.printCompactArray(compactArray);

    }

    public String[][] diXmlRecursiveRead(Iterator<Element> list, String[] columnNames, String[][] compactArray,
            Integer arrayCount) {

        String[] columns = columnNames;

        // append stuff to array
        // compactArray[a][arrayCount] =
        compactArray[arrayCount] = columnNames;

        // Method calls itself with a new level of the child
        // this is a _recursion step_
        // OR
        // Method returns the compactArray!
        // this is the _recursion ancor_
        if (arrayCount < threshhold) {

            System.out.println("returning diXmlRecursiveRead");

            return diXmlRecursiveRead(null, columns, compactArray, ++arrayCount);//increment arrayCount BEFORE passing ;) - else it gives stackoverflow (haha)

            // Java want me to return here!!
        } else {
            System.out.println("returning the compactArray");
            // _recursion anchor_
            return compactArray; // this marks the end of the recursion
            // values start to be passed back from here
            // you might want to specify another condition for the anchor to be
            // thrown ;)
        }
    }

    public void printCompactArray(String[][] compactArray){
        for(int count = 0; count < compactArray.length; count++){
            for(int inside=0; inside < compactArray[0].length; inside++) //warning assuming all Arrays in compactArray have the same length
            System.out.println(compactArray[count][inside]);
        }
    }

}

这会产生:

返回diXmlRecursiveRead

返回diXmlRecursiveRead

返回diXmlRecursiveRead

返回compactArray

您好

世界

您好

世界

您好

世界

您好

世界

希望这有助于^^ - d

答案 2 :(得分:0)

我认为您可能需要为方法添加默认返回值。 当'if'测试失败时,编译器需要知道要返回的值。

答案 3 :(得分:0)

你可以在最后添加一个返回值,只是为了让编译器放松。发生这种情况是因为,如果“if”子句为false,则不从此函数返回任何内容。我想这是一个基本案例回归,对吗?

答案 4 :(得分:0)

变化:

    // Method calls itself with a new level of the child
    diXmlRecursiveRead(element.getChildren().iterator(), columns, compactArray, arrayCount++);

    // Method calls itself with a new level of the child
    return diXmlRecursiveRead(element.getChildren().iterator(), columns, compactArray, arrayCount++);

请注意添加的return di...

如果方法返回一个值,那么通过代码的所有路由必须返回一些东西。在你的情况下,只有最深层次的递归才会返回一些东西。所有其他人只会丢掉所发现的价值。