【发布时间】:2017-07-07 14:48:46
【问题描述】:
我已经创建了不同类型的对象,例如 object1 object2 等。现在,如何将这些对象存储到一个数组中并打印出该数组?下面的想法不起作用。
Buch buch = new Buch("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
System.out.println(buch.toString());
//5 Objekte erstellen
/*2*/Buch buch2 = new Buch("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
System.out.println(buch2.toString());
/*3*/Buch buch3 = new Buch("Check this out", "oke", "DE 67892011789", 50, 1234f);
System.out.println(buch3.toString());
/*4*/Buch buch4 = new Buch("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
System.out.println(buch4.toString());
/*5*/Buch buch5 = new Buch("IDK", "IDK2", "DE 47740710974691", 50, 1234f);
System.out.println(buch5.toString());
Buch[] arr = new Buch[5];
for(int i = 0; i<5; i++){
arr[i] = new Buch();
}
for(int i = 0; i < arr.length; i++){ //toString method exists an it works
System.out.println(arr[i].toString());
}
输出:
标题:Ein Mann ein Wort 作者:Baba Isi ISBN:DE 1234567890 Seitenzahl:50 Preis:1234.0
标题:想粉碎作者:粉碎它 ISBN:DE 5461563259 Seitenzahl:50 Preis:1234.0
标题:Smash Me 作者:oke ISBN:DE 67892011789 Seitenzahl:50 Preis:1234.0
标题:Got ya Autor:catch ya ISBN:DE 678198771890 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
标题:IDK 作者:IDK2 ISBN:DE 47740710974691 Seitenzahl:50 Preis:1234.0
【问题讨论】:
-
您的代码应该可以工作。你得到什么错误?
-
我有一个错误,因为我忘记了“;”在for循环中打印出数组。现在我修复了它,我的代码有输出:
-
我有一种预感,你的字段都被声明为
static。 -
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。
标签: java arrays object tostring