我正在尝试递归地构建一个字符串,但它不是很有效
我的代码看起来像这样
public void UpdatePrintList(ArrayList<Node> closedList, ArrayList<Node> openList)
{
if(count <= iterations)
{
String line1 = "";
for(int i = 0; i < closedList.size(); i++)
{
if(i > 0)
{
line1 = line1 + "-";
}
line1 = line1 + closedList.get(i).GetMovement();
}
line1 = line1 + " " + closedList.get(closedList.size()-1).GetG() + " " + closedList.get(closedList.size()-1).GetHeuristic() + " " + closedList.get(closedList.size()-1).GetF();
printList.add(line1);
//*****************************************************************
String line2 = "OPEN ";
for(int i = 0; i < openList.size(); i++)
{
line2 = FindEarlierNode(openList.get(i), line2);
}
System.out.println(line2);
}
count++;
}
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
else
{
FindEarlierNode(varNode.OpenedBy(), varString);
}
varString = varString + varNode.GetMovement() + "-";
return varString;
}
奇怪的是,我知道这个if语句
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
正确运行,因此函数确实到达最早的节点。但它并没有增加字符串。代码运行但没有返回任何内容。 GetMovement只返回一个或两个字符串。输出应如下所示:
OPEN S-R S-RD S-D
但它看起来像这样:
OPEN D-DL-L -
有人可以帮忙吗?
答案 0 :(得分:0)
管理完成它。这给了我想要的输出:
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() != null)
{
varString = varString + varNode.GetMovement() + "-";
return FindEarlierNode(varNode.OpenedBy(), varString);
}
return varString += varNode.GetMovement() + " ";
}
谢谢大家。