gpt4 book ai didi

java - 将数组转换为 readObject 时出现 ClassCastException

转载 作者:行者123 更新时间:2023-12-01 11:14:05 26 4
gpt4 key购买 nike

我必须运行这个对象 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 中,如下所示:

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

关于java - 将数组转换为 readObject 时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com