2
나는 파일에서 숫자를 읽고 그 평균을 계산하는 프로그램을 작성 중이다. 그러나 런타임에 아래 오류가 나타납니다. 코드에 표시된대로 캐스팅을 사용하여 수정하려고했지만 도움이되지 않았습니다.평균을 계산하는 요소에 액세스하는 Java arraylist
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)
코드 : numbers
이 String
개체를 포함
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();
}
}
}