构造函数调用Arraylist

时间:2018-11-16 08:39:56

标签: java

我创建了一个ArrayList并尝试在myAnalyzer上调用getAverage方法,并将myClassroom指定为参数(参数)。但这没有解决 它给出以下错误,

GradeAnalyzer.java:40: error: method getAverage in class GradeAnalyzer cannot be applied to given types;

myAnalyzer.getAverage(myClassroom);
        ^
required: no arguments
found: ArrayList<Integer>
reason: actual and formal argument lists differ in length
1 error

代码:

import java.util.ArrayList;

public class GradeAnalyzer{
    //constructor
    public GradeAnalyzer(){
    }
    //method get average created returns int
    public int getAverage(){
        ArrayList<Integer> grades = new ArrayList<Integer>();
        if(grades.size() < 1){
            System.out.println("Arraylist is empty");
            return 0;
        }else{
            int sum = 0;      
            for(Integer grade :grades){
                sum = grade + sum;
            }
            int average = sum/grades.size();
            System.out.println(average);
            return average;
        }
    }
    public static void main (String[] args){
        ArrayList<Integer> myClassroom = new ArrayList<Integer>();
        myClassroom.add(98);
        myClassroom.add(92);
        myClassroom.add(88);
        myClassroom.add(75);
        myClassroom.add(61);
        myClassroom.add(89);
        myClassroom.add(95);
        System.out.println(myClassroom);
        GradeAnalyzer myAnalyzer = new GradeAnalyzer(); 
        myAnalyzer.getAverage(myClassroom);
    }
}

1 个答案:

答案 0 :(得分:7)

您的getAverage()方法没有参数。相反,您可以在其中创建一个新的空列表。
更改为

public int getAverage(List<Integer> grades){
    if(grades.size() < 1){
    ...
}