[英]ClassCastException when casting array to readObject
我必須運行對象Student的數組(有3個學生):
try
{
out = new ObjectOutputStream (new BufferedOutputStream (new FileOutputStream ("Students.dat")));
out.writeObject(s[0]);
out.writeObject(s[1]);
out.writeObject(s[2]);
out.close();
}
catch (IOException e)
{
System.out.println("Error writing student data to file.");
}
}
並且每個Student對象必須設置如下:
for (int i = 0; i<3; i++)
{
System.out.println("The following information applies to student " + (i+1));
System.out.println("What is the student's name?");
String name = input.nextLine();
if (i == 0)
{
System.out.println("Please enter the name again.");
}
name = input.nextLine();
System.out.println("What is the Social Security Number of this student?");
String ssn = input.next();
System.out.println("How many courses has the student completed?");
int numCourses = input.nextInt();
int [] grades = new int [numCourses];
int credits = (5*numCourses);
double points = 0;
for(int k = 0; k<numCourses; k++)
{
System.out.println("Type a number to represent the letter grade of course " + (k+1) + ". Type 1 for an A. Type 2 for a B. Type 3 for a C. Type 4 for a D. Type 5 for an F.");
grades[k] = input.nextInt();
switch (grades[k])
{
case 1:
points += 4;
break;
case 2:
points += 3;
break;
case 3:
points += 2;
break;
case 4:
points += 1;
break;
case 5:
break;
}
s[i] = new Student (name, ssn, numCourses, grades, credits);
}
}
運行這些行時,我不斷收到ClassCastException:
Object obj = new Object();
obj = in.readObject();
Student[] ns = (Student[])obj;
異常如下所示:
java.lang.ClassCastException: UnitSeven.Student cannot be cast to [LUnitSeven.Student;
at UnitSeven.StudentGPA.main(StudentGPA.java:21)
第21行是上述代碼中的最后一行。 有誰知道如何解決此問題,以便我可以正確投放? 在此先感謝您的幫助。
您正在閱讀一個Student
但試圖將其轉換為Student[]
。 只需刪除數組引用:
Student s = (Student)obj;
這是因為您將數組的每個元素ObjectOutputStream
存儲在ObjectOutputStream
,如下所示:
out = new ObjectOutputStream (new BufferedOutputStream (new FileOutputStream ("Students.dat")));
//you write each reference of Student
out.writeObject(s[0]);
out.writeObject(s[1]);
out.writeObject(s[2]);
out.close();
如果您希望/需要將其讀取為數組,則也將其存儲為數組:
out = new ObjectOutputStream (new BufferedOutputStream (new FileOutputStream ("Students.dat")));
out.writeObject(s);
out.close();
因此,您可以正確閱讀它:
Object obj = new Object();
obj = in.readObject();
Student[] ns = (Student[])obj;
或一行:
Student[] ns = (Student[])in.readObject();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.