因此,对于我使用java编程的课程,我想练习一下。我制作了一个关于行星的项目。我有4个行星,每个行星都包含信息。我做了一个“构造函数”类Planet:
public class Planet {
String name;
int number;
String color;
int width;
public Planet(String name){
this.name = name;
}
public void Number(int Number){
number = Number;
}
public void Color(String Color){
color = Color;
}
public void Width(int Width){
width = Width;
}
public void printPlanet(){
System.out.println("Name:"+ name );
System.out.println("Number:" + number );
System.out.println("Color:" + color );
System.out.println("Width:" + width);
}
}
和此类型的其他类(总数= 4)代表行星:
public class Earth {
public static void main(String args[]){
Planet earth = new Planet("Earth");
earth.Number(2);
earth.Color("Blue");
earth.Width(47000);
}
}
但现在我想用简单的代码创建一个简单的文件,将所有行星的所有信息输出到一起。我知道我可以把行星文件中的所有代码放在一个但是它太多了,我想要一个包含一个或两个输出所有信息的方法/构造函数的简单文件。感谢
答案 0 :(得分:2)
按建议对Planet类进行更改
public class Planet {
private String name;
private int number;
private String color;
private int width;
public Planet(String name, int number, String color, int width) {
this.name = name;
this.number = number;
this.color = color;
this.width = width;
}
public void Number(int Number) {
number = Number;
}
public void Color(String Color) {
color = Color;
}
public void Width(int Width) {
width = Width;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Planet [name=" + name + ", number=" + number + ", color="
+ color + ", width=" + width + "]";
}
}
对于初始化部分
public static void main(String[] args) {
Planet earth = new Planet("Earth", 2, "Blue", 47000);
Planet pluto = new Planet("Pluto", 9, "Blue", 47000);
Planet mars = new Planet("Mars", 5, "Blue", 47000);
Planet other = new Planet("Other", 1, "Blue", 47000);
System.out.println(earth);
System.out.println(pluto);
System.out.println(mars);
System.out.println(other);
}
答案 1 :(得分:1)
嗯,首先你需要发起行星的实例。在你的代码中它是这样的(使用上面给出的和更新类):
public class TestPlanets {
public static void main (String [] args) {
Planet earth = new Planet("Earth", 2, "Blue", 47000);
Planet pluto = new Planet("Pluto", 9, "Blue", 47000);
Planet mars = new Planet("Mars", 5, "Blue", 47000);
Planet venus = new Planet("Venus", 1, "Blue", 47000);
// make an list of the planets: (called planets)
ArrayList<Planet> planets = new ArrayList<Planet>();
planets.add(earth);
planets.add(pluto);
planets.add(mars);
planets.add(venus);
// and now magic:
for (int i = 0; i < planets.size(); i++) {
System.out.println(planets.get(i).toString());
}
}
}
现在我希望你了解它是如何工作的;)Java文档和教程非常棒!