我有两个类。一个名为 Cat 的类,包含猫的名字、出生年份和体重(以公斤为单位)。我有一个名为 Cattery 的类,它是一个数组。我想将 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();
}
}
最佳答案
只需编辑“addCat”方法即可将对象从参数传递到 ArrayList。
public void addCat(Cat name)
{
cats.add(name);
}
关于java - 如何将方法调用到对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941350/