本文介绍了如何在Java中使用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
}
return的toString();
$ / code $ / pre
$ b $ p增加行星类型
public class Planet {
字符串名称;
int月亮;
$ b $ public Planet(String name,int moons)
{
this.moons =卫星;
this.name = name;
public String toString(){
returnThe Planet+ name +Has+ moons +Moon(s)\r\\\
;
$ b
解决方案在 Planet 类中覆盖 toString()方法,并使用下面的代码:
public String toString(){
String result =;
for(int i = 0; i< planets.length; i ++){
result + = planets [i] .toString(); //添加逗号,如果你需要分开它,
//最重要的是处理空值
}
返回结果;
}
I have array in String. I want to use for loop to print all of the objects. I was under the impression this would be done by making for loop then returning the String. I am not sure what I need to change to accomplish this.Following is my effort:
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(); } }ADDED PLANET CLASS
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 "; } }解决方案Override toString() method in Planet class, and use below code :
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; }
这篇关于如何在Java中使用for循环打印所有数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!