2014-11-15 4 views
0

두 클래스가 있습니다. 고양이 이름, 출생 연도 및 체중을 킬로로 유지하는 Cat이라는 클래스. 배열 인 Cattery라는 클래스가 있습니다. Cat 클래스의 고양이를 배열에 입력하고 싶습니다. 각 고양이는 Kilos에서 자체 이름, 출생 연도 및 체중을 갖습니다. 어떻게해야합니까? 고맙습니다.메서드를 개체 배열로 어떻게 호출합니까?

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(); 
} 
} 
+3

음식 깡통을 두드리는 것이 더 효과적 일지 모르지만 "여기 키티"라고 해보십시오. –

+0

'cats.add (새 고양이 (...))'를 호출 하시겠습니까? –

답변

0

무엇을 당신이하려고하는 것은 당신의 Cattery에서 선언 된 cats 목록에 고양이를 추가 할 것 같다. 다른 대답은 이미 필요한 수정을 기록합니다. 실제로 고양이를 목록에 넣으려면 addCat 메서드를 수정해야합니다. 고양이 이름을 추가하지 않고 실제 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()); 
    } 
} 
+1

'388.87' ?? 얼마를 먹이세요? – ajb

+1

@ajb Milo는 대식 고양이입니다. – Josh

+1

나는 "소비 준비가 된 고양이 *"의 수가 더 걱정된다. 정기적으로 ** 먹어 ** 고양이? –

1

"addCat"메서드를 편집하여 개체를 인수에서 ArrayList로 전달하십시오.

public void addCat(Cat name) 
{ 
    cats.add(name); 
} 
관련 문제