大家好,提前感谢您的帮助。 我有一个在控制台中打印的递归方法。
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
传递给该方法。
关于java - 如何转换打印到控制台的递归方法,使其返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858122/