# How do I get an average using an Array?

• April 21st, 2014, 06:37 PM
cheshire
How do I get an average using an Array?
I'm trying to calculate the average of grades that a user puts in.

Here is my code so far:
Code Java:

``` public static void main(String[] args) {   Scanner input = new Scanner (System.in);   System.out.println("Please enter an array of grades seperated bt a comma."); input.nextLine(); String arrayOfGrades = "100,50,100"; String[] grades = arrayOfGrades.split(",");       }   public static double average(String[] grades){   double sum=0; double average;   for (int i=0; i<grades.length;i++){ sum += grades[i]; } average = sum/grades.length;   System.out.println("Your grade average is:" +average); }```

I think I'm on the right track, the only big error I'm really getting is the line: sum += grades[i]. It's saying string can not be converted into a double.
• April 21st, 2014, 06:46 PM
Norm
Re: How do I get an average using an Array?
Quote:

string can not be converted into a double.
Basically that's true about what the compiler can NOT do. The programmer can write code that uses the Double class's parse method to convert a String of digits (like "12.34") to a double.
• April 22nd, 2014, 05:46 AM
jocdrew21
Re: How do I get an average using an Array?
Why are you using a string? You should always assume a double when dealing with grades. Just make a double array or even better an ArrayList.

Code Java:

`parseDouble`
returns a primitive double containing the value of the string:

"Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double."

Code Java:

`valueOf`
returns a Double instance, if already cached, you'll get the same cached instance.

"Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values."

To avoid the overhead of creating a new Double object instance, you should normally use valueOf