2015-08-16 116 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

這是一個不同的問題,必須在新的問題/答案 –