Java 如何转换打印到控制台的递归方法,使其返回字符串?

Java 如何转换打印到控制台的递归方法,使其返回字符串?,java,recursion,Java,Recursion,大家好,提前谢谢你们的帮助。 我有一个在控制台中打印的递归方法 private void printPath(Vertex destiny) { if (destiny.getPrevious() != null) { printPath(destiny.getPrevious()); System.out.print(" to "); } System.out.print(destiny.getNa

大家好,提前谢谢你们的帮助。 我有一个在控制台中打印的递归方法

private void printPath(Vertex destiny) {
        if (destiny.getPrevious() != null) {
            printPath(destiny.getPrevious());
            System.out.print(" to ");
        }
        System.out.print(destiny.getName());
    }
但是现在我需要返回连接的字符串,而不是打印。 我这次尝试很失败

private String printPath(Vertex destiny, String concat) {
        if (destiny.getPrevious() == null) {
            return " , " + concat;
        } else {
            return printPath(destiny, (destiny.getName() + " " + concat));
        }
    }
但我不能让它工作,它给了我一个StackOverflowException

编辑: 控制台的输出是,例如: “西班牙到德国到波兰到希腊”。。。
这与我希望以字符串形式返回的内容相同。

您的方法没有正确终止,请尝试以下操作:

private String printPath(Vertex destiny, String concat) {
    if (destiny.getPrevious() == null) {
        return " , " + concat;
    } else {
        return printPath(destiny.getPrevious(), (destiny.getName() + " " + concat));
    }
}
destiny.getPrevious()
而不是
destiny
传递给该方法。

如何:

private StringBuilder printPath(Vertex destiny, StringBuilder path) {
        if (destiny.getPrevious() != null) {
            printPath(destiny.getPrevious(), path);
            path.append(" to ")  ;
        }
        path.append(destiny.getName());
        return path;
    }

如果您希望输出为“西班牙到德国到波兰到希腊”

案例1:如果destiny.getPrevious()==null,那么它将只返回destiny.getName(),与您的第一个代码相同

案例2:如果destiny.getPrevious()!=null,则将第一个元素返回到最后一个元素

private String printPath(Vertex destiny, String concat) {
    if (destiny.getPrevious() == null) {
        return destiny.getName() + concat;
    } else {
        return printPath(destiny.getPrevious(), (" to " + destiny.getName() + concat));
    }
}

如果您也提供控制台的输出(您现在得到什么以及您期望得到什么),则更容易理解。在第一个代码示例中,您在
getPrevious()
上调用
printPath
。在第二种情况下,您没有这样做。在第二个代码中,当第一次调用
printPath
时,第二个参数
concat
的值是多少。我相信Sriram是正确的。看看你传递回printPath的内容,如果第一个顶点有一个先前的顶点,你的原始答案将导致一个无限循环。非常感谢@SriramKailasam实际上我忘记在第二次返回时包含getPrevious(),这导致了一个无限循环。