2013-03-26 93 views
0

我試圖在傳遞一個數組對象數組的類中創建一個靜態方法,並返回數組中的對象的平均值。創建一個方法來返回數組的值的平均值

public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
      sum = sum + people[i]; 
    double calcAverage() = sum/people.length 
    System.out.println(people.calcAverage()); 
} 

該代碼是越來越編譯錯誤,但我正朝着正確的方向?

+0

看起來,它會有一些無限的遞歸,一旦你得到它的編譯。把'println'移到其他地方。也許在'main'中。 – nattyddubbs 2013-03-26 02:08:56

+1

double calcAverage()是錯誤的,聲明一個變量double avgVal = sum/people.length;並打印avgVal – Abi 2013-03-26 02:09:35

+0

人們如何/在哪裏宣佈? – 2013-03-26 02:23:52

回答

1
public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
      sum = sum + people[i]; 
    double calcAverage() = sum/people.length 
    System.out.println(people.calcAverage()); 
} 

變化

double calcAverage() = sum/people.length 

double average = sum/(double)people.length; 

(聲明一個新變量的正確方法)

變化

 System.out.println(people.calcAverage()); 

return average; 

(如果你想打印調用該函數的結果,你應該總是做它的功能,例如外做到在main調用該函數和存儲返回的結果)

後,所以我們有:

public static double calcAverage() { 
    int sum = 0; 
    for (int i=0; i < people.length; i++) 
    { 
     sum = sum + people[i]; 
    } 
    double average = sum/(double)people.length; 
    return average; 
} 
+0

嗯..由於某種原因,它仍然不接受它..試圖找出爲什麼 – aiuna 2013-03-26 02:19:10

+0

@aiuna你得到了什麼確切的錯誤信息和行號? – Patashu 2013-03-26 02:19:40

+0

想通了,非常感謝! – aiuna 2013-03-26 02:27:14

1

你的親密。雖然我看到一些錯誤。

首先你的總和= sum + people [i];

people [i] returns object is not an integer,so add a object to a integer wont work。

秒,你在calcAverage方法內調用calcAverage(),這可能不是你想要做的。這樣做被稱爲遞歸,但我認爲你應該在calcAverage()之外調用方法。

1
// pass people as a parameter 
public static double calcAverage(int[] people) { 
    // IMPORTANT: this must be a double, otherwise you're dividing an integer by an integer and you will get the wrong answer 
    double sum = 0; 
    for (int i=0; i < people.length; i++) { 
     sum = sum + people[i]; 
    } 
    // remove the() 
    double result = sum/people.length; 
    System.out.println(result); 

    // return something 
    return result; 
} 


// example 
int[] myPeople = {1,2,3,4,5,6,7,8}; 
double myPeopleAverage = calcAverage(myPeople); 
+0

必須修復我的一些東西部分,非常感謝 – aiuna 2013-03-26 02:27:31

相關問題