如何在Planet类中覆盖toString?

时间:2013-12-08 09:57:24

标签: java arrays eclipse for-loop foreach

我知道一个吸气剂安装器会起作用!我知道有很多人告诉我覆盖toString,但严酷的事实是,当有一个对象数组和一个循环时,我不知道如何覆盖它!

import java.util.Scanner;
public class Planet {

    private String[] planetName;
    private String SurfaceMaterial;
    private double daysToOrbit;
    private double diameter;
    private String globalMagnet;

public Planet(){
    planetName=new String[8];
    SurfaceMaterial="";
    daysToOrbit=0;
    diameter=0;
    globalMagnet="";
}

public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter,String globalMagnet){
    this.planetName=planetName;
    this.SurfaceMaterial=SurfaceMaterial;
    this.daysToOrbit=daysToOrbit;
    this.diameter=diameter;
    this.globalMagnet=globalMagnet;
}

public void setPlanetName(){
    Scanner in=new Scanner(System.in);

    Planet solar[]=new Planet[8];
    for(int i=0;i<solar.length;i++){
        solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter,globalMagnet);
        System.out.println("\nEnter Planet Name at "+i+":");
        planetName[i]=in.next();
        System.out.println("Enter Surface Material at "+i+":");
        SurfaceMaterial=in.next();
        System.out.println("Enter Days to Orbit at "+i+":");
        daysToOrbit=in.nextDouble();
        System.out.println("Enter Diameter at "+i+":");
        diameter=in.nextDouble();
        System.out.println("Global magnetic field present at "+i+"?\n\n");
        globalMagnet=in.next();
    }
    System.out.println("Planets sorted by diameter:\n\n");
    System.out.println("Name:                                  "+planetName[0]);

    for(Planet pl:solar){
        System.out.println(pl);
    }
    /*for(int i=0;i<=solar.length;i++){
    System.out.println("Name:                                  "+planetName[i]);
    System.out.println("Surface Material:                      "+solar[i].SurfaceMaterial);
    System.out.println("Days to orbit Sun:                     "+solar[i].daysToOrbit);
    System.out.println("Diameter:                              "+solar[i].diameter);
    System.out.println("Global Magnetic Field:                 "+solar[i].globalMagnet+"\n\n");
    */
    }
}

2 个答案:

答案 0 :(得分:0)

您需要在对象Planet中编写toString()方法。 如果你不这样做,toString会打印对象的地址。

答案 1 :(得分:0)

您的代码中存在几个问题。首先是您正在以错误的方式编写foreach循环。应该是

 for(Planet pl:solar){
        System.out.println(solar);
    }

第二个问题是你将planetName定义为array.it将是一个字符串。

创建一个getter来获取Planet名称并像上面的foreach循环一样调用