Java中Group类嵌套结构toString方法缩进异常问题
嵌套Group的toString层级缩进问题
我在可容纳Figure及其他Group的Group类中实现了toString方法,期望输出带有层级缩进的嵌套Group文本结构,但实际调用时所有子元素仅显示一个制表符缩进,无法呈现预期的层级效果。尝试将制表符替换为双制表符后,问题仍未解决。
预期输出
Group consists of: Group consists of: Rectangle with center at (20.0, 10.0), and width: 15.0, height: 15.0, angle: 45.0 Rectangle with center at (0.0, 0.0), and width: 7.0, height: 19.0, angle: 90.0 Group consists of: Circle with center at (100.0, 100.0) and radius: 1.0 Circle with center at (5.0, 0.0) and radius: 9.0 Rectangle with center at (10.0, 10.0), and width: 10.0, height: 40.0, angle: 0.0 Circle with center at (0.0, 0.0) and radius: 55.0
实际错误输出
Group consists of: Group consists of: Rectangle with center at (10.0, 10.0), and width: 10.0, height: 15.0, angle: 0.0 Rectangle with center at (20.0, 10.0), and width: 15.0, height: 15.0, angle: 45.0 Rectangle with center at (0.0, 0.0), and width: 7.0, height: 19.0, angle: 90.0 Group consists of: Circle with center at (0.0, 0.0) and radius: 10.0 Circle with center at (100.0, 100.0) and radius: 1.0 Circle with center at (5.0, 0.0) and radius: 9.0
初始实现代码
public String toString() { StringBuilder str = new StringBuilder("Group consists of:\n"); for (BaseFigure figure : this.group) { str.append("\t").append(figure.toString()).append("\n"); } return str.toString(); }
尝试修改后的代码
public String toString() { String str = "Group consists of:\n"; for (BaseFigure figure : this.group) { if (figure instanceof Group) { String newStr = figure.toString(); str += newStr.replace("\t", "\t\t"); } else { str += figure.toString(); } } return str; }
解决方案
核心问题是没有将当前层级的缩进传递给子Group,导致子Group的所有内容仅使用自身的基础缩进,无法叠加父级的缩进层级。正确的做法是通过重载toString方法,增加缩进参数来传递层级信息,递归调用时加深缩进:
修正后的代码
// 对外暴露的无参方法,初始化递归的缩进为空 @Override public String toString() { return toString(""); } // 私有递归方法,接收当前层级的缩进参数 private String toString(String indent) { StringBuilder sb = new StringBuilder(indent + "Group consists of:\n"); // 子元素的缩进是当前缩进追加一个制表符 String childIndent = indent + "\t"; for (BaseFigure figure : this.group) { if (figure instanceof Group) { // 递归调用子Group的带参toString,传递子层级缩进 sb.append(((Group) figure).toString(childIndent)); } else { // 普通Figure直接使用子层级缩进拼接内容 sb.append(childIndent).append(figure.toString()).append("\n"); } } return sb.toString(); }
说明
- 用带缩进参数的私有方法处理递归逻辑,每次进入子Group时,将当前缩进加上一个制表符传递下去,确保子Group的所有内容基于父级缩进再加深一层。
- 无参的toString作为对外接口,初始缩进为空字符串,保证最外层Group没有前置缩进。
- 普通Figure元素直接使用当前层级的子缩进,确保与同一层级的Group内容对齐。
这样就能生成符合预期的层级缩进结构了。
内容的提问来源于stack exchange,提问作者Fischer Benkovscki
相关产品推荐
相关产品推荐

