I am writing a program that reads numbers from a file and calculates the average of them. However, I am getting the error shown below at run-time. I tried to fix it using the casting to double as shown in the code but it did not help.
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at ReadFile.main(ReadFile.java:34)
at __SHELL40.run(__SHELL40.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at ReadFile.main(ReadFile.java:34)
at __SHELL41.run(__SHELL41.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at ReadFile.main(ReadFile.java:33)
at __SHELL42.run(__SHELL42.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at ReadFile.main(ReadFile.java:33)
at __SHELL43.run(__SHELL43.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
Code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile
{
public static void main(String[] args)
{
try
{
Scanner input = new Scanner("n.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
ArrayList numbers = new ArrayList();
int index=1;
while (input.hasNextLine()) {
String line = input.nextLine();;
numbers.add(line);
System.out.println(index + " : " + line);
index++;
}
input.close();
double sum = 0.0;
double average;
for (int j = 0; j < numbers.size(); j++)
{
sum = sum + (double) numbers.get(j) ; //My guess is that this line is invoking the error
}
average = sum/numbers.size();
System.out.println(average);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}