0

我正在尝试执行以下操作:

一种将猫的 ArrayList 中所有猫的腿合计的方法。

但是,我似乎无法将数组中猫腿的总数相加,或将其显示在控制台上。

   public static int getNumOfLegs()
{

    return numOfLegs;
}

public void setNumOfLegs(int numOfLegs)
{
    this.numOfLegs = numOfLegs;

}



   public static int totalNumOfLegs(ArrayList<Cat> catList)
{
    int total = 0;
    for (Cat c: catList)
    {
        total = total + getNumOfLegs();
    }


    return total;

}

非常感激。

4

2 回答 2

6

改变:

total = total + getNumOfLegs();

至:

total = total + c.getNumOfLegs();
于 2013-09-22T02:44:06.227 回答
0

假设每只猫的腿数不同 - 您需要单独计算每只猫的腿数。为此,您需要在 for 循环中使用 cat 对象(您将其命名为 c)来获取腿数。(已建议为 c.getNumOfLegs();

此外,您的静态方法 getNumOfLegs 和 setNumOfLegs 应该在 Cat 的类定义中(当然不是静态的)

于 2013-09-22T03:14:34.500 回答