2016-12-04 99 views
-1

我的數組應該傳遞給一個函數,但是我的程序有錯誤,不能編譯。我究竟做錯了什麼?將數組傳遞給函數時出錯。它不能編譯

  1. 我正在上線13的錯誤: 「a1e.averData(分數,MAX_SIZE);」
  2. 錯誤狀態,「非靜態變量分數不能從 靜態上下文引用。分配返回值到新變量」
  3. 我也嘗試將返回值分配給新變量。它看起來像這樣:「float averData = a1e.averData(scores,MAX_SIZE);」
  4. 錯誤更改爲:「非靜態變量分數不能從靜態上下文中引用非靜態變量MAX_SIZE不能從靜態上下文中引用」
  5. 我試着將它從主要移動到其他位置在程序中,但它似乎並不想爲我工作,我不確定如何解決它。

這裏是我的代碼:

package array1example; 

    public class Array1example 
    {  
     int i, sum; 
     float avg; 
     int scores[]; 
     int MAX_SIZE = 0; 
     /** 
     * 
     * @param args 
     */ 
     public static void main(String[] args) 
     { 
     /* An example of an array being passed to a function 
      This program stores integers in an array 
      and computes their average*/ 


      Array1example a1e = new Array1example(); 
     } 

     public Array1example() 
     { 
     this.scores = new int[]{5, 5, 12, 17, 11}; 
     a1e.averData(scores,MAX_SIZE); 
     } 
     private float averData(int[] scores1, int MAX_SIZE1) 
     { 

      int size = 0; 
      for(i=0, sum=0; i<size; i++) 
      { 
      System.out.println("Score " + " = " + scores1[i]); 
      sum += (scores1[i]); 
     } 
      avg = sum/i; 
      System.out.println("Average score: " + avg); 
     return avg;   
     } 

     } 
+0

我想你已經改變了代碼,不再反映了這個錯誤,並且通過在構造函數中使用'a1e'來增加更多問題。我相信最初的問題是試圖在'main'裏面傳遞'scores',這是不允許的。你需要做'a1e.scores/MAX ...' – ChiefTwoPencils

+0

哎呀!不用喊! –

回答

1

在構造函數不能使用a1e.averData(scores,MAX_SIZE);, 而是變成averData(scores,MAX_SIZE);

+0

您的構造函數類似於靜態上下文。然而你的a1e對象是非靜態的。 –

+0

這是因爲'a1e'是你'main'方法中的一個局部變量,所以你不能在該方法之外使用它。您也不需要:在您的構造函數中,您位於要構造的對象內部,因此您可以在沒有點標記的情況下調用對象的方法。 –

+0

我曾試着做你所建議的,但它仍然不能編譯。 –