gpt4 book ai didi

java - 如何将换行符添加到多树的toString

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:07 26 4
gpt4 key购买 nike

有这样一个结构:

public class TreeNode {

private String key;
private List<TreeNode> children;
....

我覆盖了 toString() 函数

@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"--- >"+children.toString()+"/n";
}
}
return treeStructure;
}

然后我测试结果:

public static void main(String[] args) {
TreeNode node = new TreeNode();
node.setKey("root");
List<TreeNode> children = new ArrayList<TreeNode>();
TreeNode child1 = new TreeNode();
child1.setKey("child1");
TreeNode child2 = new TreeNode();
child2.setKey("child2");
children.add(child1);
children.add(child2);
List<TreeNode> grandchildren = new ArrayList<TreeNode>();
TreeNode grandchild = new TreeNode();
grandchild.setKey("grandchild");
grandchildren.add(grandchild);

node.setChildren(children);
child1.setChildren(grandchildren);

System.out.println(node);

}

但是当我运行它时输出是:

TreeNode [key=root]--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n

我怎样才能像这样在输出中添加换行符:

TreeNode [key=root]--->TreeNode [key=child1]--->TreeNode [key=grandchild]
--->TreeNode [key=child2]

但是现在 child1 显示了两次,结果中没有添加换行符。

================================我改了功能:

@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"\n"+"-->"+children.toString()+"\n";
}
}
return treeStructure;
}

那么输出是:

TreeNode [key=root]
--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]

--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]

为什么 child 重复两次,“,”从哪里来?

最佳答案

使用\n代替/n

treeStructure = treeStructure + "--- >" + children.toString() + "\n";

关于java - 如何将换行符添加到多树的toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10498811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com