【发布时间】:2019-01-25 12:04:37
【问题描述】:
我想打印我的数组列表的所有元素。 Eclipse 没有显示错误,但它没有显示我在控制台中添加的元素。你能告诉我我做错了什么吗? 控制台显示:
类型:机器人 编号:8282 名称R2D2 HumanoiderRoboter@15db9742 HumanoiderRoboter@6d06d69c HumanoiderRoboter@7852e922 HumanoiderRoboter@4e25154f
机器人类:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter 类:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
【问题讨论】:
-
将 toString() 方法添加到您的 HumanoiderRoboter
-
但它做了什么?
-
你需要@override toString() 方法
-
似乎您的 Roboter 和子类缺少适当的 toString() 方法来满足您的需求。那个 println() 方法不理解如何显示复杂的对象。
-
在超类
Roboter中添加String toString()方法