2015-08-16 74 views
0

当我要运行这个数组对象学生(其中有3名学生):ClassCastException异常铸造阵列的readObject

 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."); 
    } 
} 

并且每个学生对象必须设定这样的:

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行是上述代码中的最后一行。有谁知道如何解决这个问题,以便我可以正确施放它?预先感谢您的帮助。

+0

你可以张贴一些更多的代码,你如何序列化对象?这三行不足以确定问题 –

+0

在那里,我编辑了它。 – Foxwood211

回答

1

您正在阅读的是单个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(); 
+0

谢谢,你的建议帮助。但是我现在正在得到一个ArrayOutOfBoundsException。我不知道如何解决它。你能帮我解决吗?以下是显示对象的代码:http://pastebin.com/pUi5gKcP 发生运行时错误的行是: 'Object cred = ns [5];' – Foxwood211

+0

这是一个不同的问题,必须在新的问题/答案 –