2016-12-04 92 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

我曾试着做你所建议的,但它仍然不能编译。 –