I have to run this array of object Student (where there's 3 students):
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.");
}
}
And each Student object must be set like this:
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);
}
}
I keep getting the ClassCastException when running these lines:
Object obj = new Object();
obj = in.readObject();
Student[] ns = (Student[])obj;
The exception looks like this:
java.lang.ClassCastException: UnitSeven.Student cannot be cast to [LUnitSeven.Student;
at UnitSeven.StudentGPA.main(StudentGPA.java:21)
And line 21 is the last line in the code mentioned above. Does anyone know how to fix this so that I can cast it properly? Thanks in advance for any help.
You're reading a single Student
but trying to cast it as an Student[]
. Just remove the array reference:
Student s = (Student)obj;
This is because you're storing each element of your array in your ObjectOutputStream
by itself, noted here:
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();
If you want/need to read it as an array, then store it as an array as well:
out = new ObjectOutputStream (new BufferedOutputStream (new FileOutputStream ("Students.dat")));
out.writeObject(s);
out.close();
So you can read it properly:
Object obj = new Object();
obj = in.readObject();
Student[] ns = (Student[])obj;
Or in a single line:
Student[] ns = (Student[])in.readObject();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.