Classroom Grades Analyzer - ArrayList Initialization


#1

Hi, I was wondering if I could get help learning how to properly initialize an arraylist for the Classroom Grades Analyzer challenge int the Java course. Below is my code

import java.util.ArrayList;

public class GradeAnalyzer {
  public GradeAnalyzer(){
    
  }
  
  public int getAverage(ArrayList<Integer> grades){
    int sum = 0;
    if (grades.size() < 1) {
      System.out.println("you suck");
      return 0;
    } else {
    	for(Integer i: grades){
      	sum += i;
    	}
    }
    int average = sum/grades.size();
    System.out.println("The average is: "+ average);
    return (average);
  }
  
  public static void main(String[] args) {
    ArrayList<Integer> myClassroom = new ArrayList<Integer>(Arrays.asList(98,92,88,75,61,89,95));
    GradeAnalyzer myAnalyzer = new GradeAnalyzer();
		myAnalyzer.getAverage(myClassroom);
    }
}

So the part I want to focus on is my attempt to initialize the array list in one line.

ArrayList<Integer> myClassroom = new ArrayList<Integer>(Arrays.asList(98,92,88,75,61,89,95));

The above fails and I get an error from the compiler saying

GradeAnalyzer.java:24: error: cannot find symbol
    ArrayList<Integer> myClassroom = new ArrayList<Integer>(Array.asList(98,92,88,75));
                                                            ^
  symbol:   variable Array
  location: class GradeAnalyzer
1 error

Looking at the error, it seems to not be able to find my variable, or the array in this case. At least, thats my understanding of why it threw this error.
However, if I change that line to this line below

    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);

Then everything works. My thought process was to reduce lines in this spot since it looks especially repetitive (although I guess for this case, it would be unnecessary), but going forward, I wanted to see what I was doing wrong in my first attempt. Thank you so much for your time!


#2

sounds like you are looking for something like this:

https://beginnersbook.com/2013/12/how-to-initialize-an-arraylist/


#3

Yes actually, thank you. I found a similar example on stackover flow. To me it looks like what I have matches the example, but in my case I run into an error.


#4

this answers the question why you get an error:

https://stackoverflow.com/questions/16742270/cannot-find-symbol-java-error

the java error indicated it couldn’t find Arrays “symbol”


#5

Ah, I thought that the first import would include that. Thank you!!!