我有数组String
。我想使用for
循环来打印所有对象。我的印象是,可以通过进行for循环然后返回来完成String
。我不确定要实现此目标需要进行哪些更改。以下是我的努力:
public class SolarSystem {
private Planet[] planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
for(int i = 0; i < planets.length; i++){
}
return toString();
}
}
新增PLANET班
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}
覆盖类中的toString()
方法Planet
,并使用以下代码:
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString(); // append comma if you need to separate it,
// and most of all handle nulls
}
return result;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句