如何将方法调用到对象数组中?

时间:2014-11-15 01:04:06

标签: java arrays object methods call

我有两节课。一个名为Cat的类,它包含猫的名字,出生年份和体重(公斤)。我有一个名为Cattery的类,它是一个数组。我想将Cat类中的cat输入到数组中。每只猫在基洛斯都有自己的名字,出生年份和体重。我该怎么做呢?谢谢。

public class Cat {

    private String name;
    private int birthYear;
    private double weightInKilos;

/**
 * default constructor
 */ 
public Cat() {   
}

/**
 * @param name
 * @param birthYear
 * @param weightInKilos
 */
public Cat(String name, int birthYear, double weightInKilos){   
    this.name = name;
    this.birthYear = birthYear;
    this.weightInKilos = weightInKilo
}

/**
 * @return the name.
 */
public String getName() {
    return name;
}

/**
 * @return the birthYear.
 */
public int getBirthYear() {
    return birthYear;
}

/**
 * @return the weightInKilos.
 */  
public double getWeightInKilos() {
    return weightInKilos;
}

/**
 * @param the name variable.
 */
public void setName(String newName) {
    name = newName; 
}

/**
 * @param the birthYear variable.
 */
public void setBirthYear(int newBirthYear) {
    birthYear = newBirthYear;
}

/**
 * @param the weightInKilos variable.
 */
public void setWeightInKilos(double newWeightInKilos) {
    weightInKilos = newWeightInKilos;
} 
}

数组类。

import java.util.ArrayList;

public class Cattery {

    private ArrayList<Cat> cats;
    private String businessName;

/**
 * @param Cattery for the Cattery field.
 */

public Cattery() {
    cats = new ArrayList<Cat>();
    this.businessName = businessName;
}

/**
 * Add a cat to the cattery.
 * @param catName the cat to be added.
 */
public void addCat(Cat name)
{
    Cat.add(getName());
}

/**
 * @return the number of cats.
 */
public int getNumberOfCats()
{
    return cats.size();
}
}

2 个答案:

答案 0 :(得分:1)

只需编辑“addCat”方法,即可将对象从参数传递给ArrayList。

public void addCat(Cat name)
{
    cats.add(name);
}

答案 1 :(得分:0)

您尝试执行的操作似乎是将猫添加到cats中声明的Cattery列表中。另一个答案已经注意到需要进行修正 - 必须修改addCat方法,然后将猫实际放入列表中。请注意,您不是要添加cat名称,而是添加实际的Cat对象。您似乎希望Cattery拥有商家名称。您可以将其传递给构造函数。

public Cattery(String businessName) {
    cats = new ArrayList<Cat>();
    this.businessName = businessName;
}
...
public void addCat(Cat cat)
{
    cats.add(cat);
}

以下是一个如何创建猫舍并随后添加猫的示例。你必须爱猫。

class CatApp{
    public static void main(String[] args) {
        Cattery cattery = new Cattery("The Delicious Cats Business");
        cattery.addCat(New Cat("Milo", 3, 388.87));
        cattery.addCat(New Cat("Otis", 2, 1.4));
        System.out.println("Total number of cats ready for consumption = " 
            + cattery.getNumberOfCats());
    }
}