创建一个计算数组平均值的方法(java)

时间:2013-03-26 02:12:59

标签: java arrays

编写一个名为calculateAverageWeight的静态方法,将其添加到Bowl类中,该类传递一个Bowl对象数组,并返回数组中Bowls的平均权重。

这是碗类:

public class Bowl {
private double weight;
private boolean empty;
private String origin; // country of manufacture

public Bowl(double w, boolean e, String origin) {
    weight = w;
    empty = e;
    this.origin = origin;
}

public double getWeight() {
    return weight;
}

public boolean getEmpty() {
    return empty;
}

public String getOrigin() {
    return origin;
}

public void setEmpty(boolean emptyStatus) {
    empty = emptyStatus;
}

public String toString() {
    return ("from " + origin + " weight: " + weight);
}

以下代码有效:

public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}

但我不明白为什么我最近的代码没有,因为它们似乎与我几乎完全相同?:

public static double calculateAverageWeight(Bowl[] bowls){
double sum=0;
double k=bowls.length;
for(int j=0; j<bowls.length; j++){
sum=sum+bowls[j].getWeight();}
double average=sum/k;
return average;}

2 个答案:

答案 0 :(得分:0)

public static double calculateAverageWeight(Bowl[] bowls)
{
    double sum=0;
    double average=0;
    for(int j=0; j<bowls.length; j++)
    {
        sum+=bowls[j].getWeight();
        average=sum/bowls.length;
    }
    return average;
}

答案 1 :(得分:0)

calculateAverageWeight 的代码没问题,但是在碗类结束时你错过了一个“}”。

此外,您的 calculateAverageWeight 方法必须位于另一个类中,因此您可能也会遗漏某些内容。你可以发布你的代码吗?