? 發問時間： 電腦與網際網路程式設計 · 1 0 年前

# java之物件導向相關問題

We need to calculate three cats’ health index

Kitty(Length = 12, Weight = 6, Age = 2)

Willie(Length = 20, Weight = 5, Age = 25)

Gina(Length = 10, Weight = 8, Age = 10)

len^+wei^/age^

len^*wei^/age^

### 1 個解答

• 生鏽
Lv 5
1 0 年前
最佳解答

你的公式二沒有完整印出來? 總之我先假設計算式

public class Cat

{

String name;

float length, weight;

int age;

public Cat(String name, float length, float weight, int age)

{

this.name = name;

this.length = length;

this.weight = weight;

this.age = age;

}

public String getName()

{

return name;

}

public float getHealthIndex1() {

return length + weight / age;

}

public float getHealthIndex2()

{

return (length + weight) / age;

}

public float getAverageHealthIndex()

{

return (getHealthIndex1() + getHealthIndex2()) / 2;

}

public static void main(String[] args) {

Cat[] cats = new Cat[3];

cats[0] = new Cat("Kitty", 12, 6, 2);

cats[1] = new Cat("Willie", 20, 5, 25);

cats[2] = new Cat("Gina", 10, 8, 10);

for (int i = 0; i < cats.length; i++) {

System.out.println(cats[i].getName());

System.out.print("index 1: ");

System.out.println(cats[i].getHealthIndex1());

System.out.print("index 2: ");

System.out.println(cats[i].getHealthIndex2());

System.out.print("average index: ");

System.out.println(cats[i].getAverageHealthIndex());

}

}

}

有問題可以補充討論。

2008-03-19 10:24:15 補充：

getHealthIndex2 的計算式改為

return length * weight / age;