我正在创建一个带有Bags 和Items的复合模式,其中Bags 可以包含Items 但Items 不能包含任何内容。
当我toString()在根上使用-method 时,我希望其中的每一个Entity都Bag以“自然语言”打印。目前看起来递归在toString()-method 中被破坏了,我不知道为什么。我尝试System.out.println(1);在while-loop之前使用,它只打印一次,这就是为什么我认为递归被破坏了。
Item-班级;
public class Item extends Entity {
public Item(String theName) {
this.name = theName;
}
public String toString() {
String output = String.format("a %s", name);
return output;
}
}
Bag-班级
import java.util.*;
public class Bag extends Entity {
private List<Entity> children = new ArrayList<Entity>();
public Bag(String theName) {
this.name = theName;
}
public void add(Entity entity) {
children.add(entity);
}
public String toString() {
String output = String.format("a %s", name);
Iterator<Entity> itemIterator = children.iterator();
output += " containing ";
Entity current = itemIterator.next();
while (itemIterator.hasNext()) {
output += current.toString();
Entity next = itemIterator.next();
if (next instanceof Item) {
output += ", ";
} else if (next instanceof Bag) {
output += " and ";
}
current = next;
}
return output;
}
}
Entity-班级;
public abstract class Entity {
protected String name;
protected int weight;
public abstract String toString();
public abstract int getWeight();
}
MyFrame包含main- 方法;
翻阅古今
万千封印
一只名叫tom的猫
相关分类