? 發問時間: 電腦與網際網路程式設計 · 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)

假設貓有兩種健康指數公式

公式一:Health index = length2 + weight2 / age2

公式二: Health index = length  weight / age2

請列印出下列資料:

每隻貓的公式一結果

每隻貓的公式二結果

每隻貓的公式一結果與公式二結果之平均

請利用物件與類別的概念來設計Cat class

已更新項目:

不好意思:

公式一:

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;

還有問題?馬上發問,尋求解答。