gpt4 book ai didi

java - 如何递归打印带缩进的分层列表

转载 作者:行者123 更新时间:2023-12-01 19:28:56 26 4
gpt4 key购买 nike

我有一个类,它由一个字符串名称和该类的其他实例(称为附件)的 ArrayList 组成。把它想象成一个可以连接到无数其他乐高积木的乐高积木。我需要在控制台中使用缩进显示此层次结构(不传递任何参数),但我不确定这样做的最佳方法:

预期输出:

+ PowerSource
+ Appliance
+ Extension
+ Module
+ Lamp
+ Appliance
+ Module

当前输出:

+ PowerSource
+ Appliance
+ Extension
+ Module
+ Lamp
+ Appliance
+ Module

我有 display() 方法,可以缩进一次,但我似乎无法让附件的附件缩进两次。任何帮助将不胜感激

package components;

import java.util.ArrayList;
import java.util.List;

public class MyTest {

private String name;
private List<MyTest> attachments;

public MyTest(String name) {
this.name = name;
attachments = new ArrayList<MyTest>();
}

public void attach(MyTest newLoad) {
attachments.add(newLoad);
}

public void display() {
System.out.print("+ " + toString() + "\n");
if (attachments.size() > 0) {
for (MyTest load : attachments) {
System.out.print(" ");
load.display();
}
}
}

@Override
public String toString() {
return name;
}

public static void main(String[] args) {
MyTest a = new MyTest("PowerSource");
a.attach(new MyTest("Appliance"));
a.attach(new MyTest("Appliance"));
MyTest l = new MyTest("Lamp");
l.attach(new MyTest("Extension"));
a.attach(l);

a.display();
}
}

最佳答案

这很正常。当进行递归调用时,程序不知道需要缩进多少。它总是缩进一个。程序需要知道列表层次结构的深度。

我的意思是,当 Appliance 调用其显示时,它必须缩进两次。因为它们的元素需要具有双重意图。但它没有这些信息。

这样你就可以创建filed int depth=0;对于基础对象。并像这样编辑附件。

public void attach(MyTest newLoad) {
newLoad.setDepth(this.depth + 1);
attachments.add(newLoad);
}

然后像这样编辑显示方法并添加缩进方法。

private void indent(int depth){
if(depth > 0){
System.out.print(" ");
indent(depth-1);
}
}
public void display() {
System.out.print("+ " + toString() + "\n");
for (MyTest load : attachments) {
this.indent(this.depth);
load.display();
}
}

我还没有对此进行测试,但您将从这些示例中了解主要思想

关于java - 如何递归打印带缩进的分层列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403192/

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