使用ArrayLists和Objects

时间:2014-09-12 00:21:46

标签: object arraylist

这是我的对象类

class Baller
{
    public String name;
    public double height;
    public double weight;
    public String country;

    public Baller()
    {
        name = "";
        height = 0;
        weight = 0;
        country = "";
    }

    public Baller(String name1, double height1, double weight1, String country1)
    {

    }

    public String getName()
    {
        return name;
    }

    public double getHeight()
    {
        return height;
    }
    public double getWeight()
    {
        return weight;
    }
    public String getCountry()
    {
        return country;
    }
}

我需要创建一个arraylist,添加每个玩家的名字,身高,体重和国家。

这是我初始化它的方式:

ArrayList<Baller> playersNames = new ArrayList<>();

这是我添加玩家信息的地方:

System.out.println("What player would you like to add (Enter Name, Height, Weight and Country)");

String name = TextIO.getlnString();
double height = TextIO.getlnDouble();
double weight = TextIO.getlnDouble();
String country = TextIO.getlnString();
players = new Baller(name, height, weight, country);
playersNames.add(players);

这是我尝试打印arraylist的方式

System.out.println("The roster is:"+playersNames);

当我将其打印出来时:Baller @ 13bad12

1 个答案:

答案 0 :(得分:0)

要输出名称,请使用:

System.out.println("The roster is:" + players.getName());

您需要了解的对象是,当您尝试直接打印它们时,将调用toString()方法。

对于您的Baller对象,它未定义,因此打印参考。如果需要,可以覆盖它以输出名称:

@Override
public String toString()
{
    return this.getName();
}

然后 System.out.println("The roster is:" + players);可行。

编辑:要打印所有播放器值,只需将它们连接到返回字符串:

@Override
public String toString()
{
    return "Name : " + this.getName() + ", Height : " + this.getHeight() + ", Weight : " + this.getWeight() + ", Country : " + this.getCountry();
}