java.lang.ClassCastException: class java.lang.String cannot be cast to class MidTermProject

Viewed 6918

I am working on a school project which basically allows the user to create a student and display the info by reading it from the file. I am using ObjectOutputStream to write and ObjectInputStream to read from the file. When going to DisplayStudent() the idea is just to display the information entered by the user when created a student but I am getting the following error:

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class MidTermProject (java.lang.String is in module java.base of loader 'bootstrap'; MidTermProject is in unnamed module of loader 'app') at MidTermProject.DisplayStudent(MidTermProject.java:247) at MidTermProject.main(MidTermProject.java:352)

I know it is related to how I am casting the following:

MidTermProject student = (MidTermProject) inputFile.readObject();

but I don't really know how should I cast it, tried some of methods but nothing, if you have any ideas would be appreciated, here is the code:

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject implements Serializable {
    
    static AtomicInteger idGenerator = new AtomicInteger(0001);
    static int id;
    
    public static int getId() {
        return id;
    }
    
    public static void CreateStudent() throws IOException {
        String FullName;
        String address;
        String city;
        String state;
        String newStudentID;
        
        Scanner keyboard = new Scanner(System.in);
        
        FileOutputStream fstream =
                new FileOutputStream("StudentInfo.dat", true);
        ObjectOutputStream outputFile =
                new ObjectOutputStream(fstream);
        
        id = idGenerator.getAndIncrement();
        String student = Integer.toString(getId());
        outputFile.writeObject(student);
        
        System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
        FullName = keyboard.nextLine();
        outputFile.writeObject(FullName);
        
        System.out.print("Address: ");
        address = keyboard.nextLine();
        outputFile.writeObject(address);
        
        System.out.print("City: ");
        city = keyboard.nextLine();
        outputFile.writeObject(city);
        
        System.out.print("State: ");
        state = keyboard.nextLine();
        outputFile.writeObject(state);
    
        outputFile.close();
        
        System.out.print("\nDone\n");
        
    }
    public static void DisplayStudent() throws IOException {
        FileInputStream fstream = new FileInputStream("StudentInfo.dat");
        ObjectInputStream inputFile = new ObjectInputStream(fstream);
        
        boolean endOfFile = false;
        
        while(!endOfFile)
        {
            try
            {
                MidTermProject student = (MidTermProject) inputFile.readObject();
                System.out.print(student + "\n");
            }
            catch (EOFException | ClassNotFoundException e)
            {
                endOfFile = true;
            }
        }
        System.out.println("\nDone");
        
        inputFile.close();
    }
    public static void main(String[] args) throws IOException {
        
        int start = 0;
        
        while(start >= 0) {
            Scanner keyboard = new Scanner(System.in);
            
            System.out.println("Here is the sample of menu choices for Main Menu.");
            
            System.out.println("\nWelcome to University Enrollment" + "\n1. Create Student" +
                                "\n2. Create Course" + "\n3. Create Enrollment" + "\n4. Edit Student" + "\n5. Edit Course"
                                + "\n6. Edit Enrollment" + "\n7. Display Student" + "\n8. Display Course" + "\n9. Display Enrollment"
                                + "\n10. Grades Sub Menu" + "\n0. --- Quit ---");
            
            System.out.println("Please enter a valid choice(1-10, 0 to Quit) :");
            int userInput = keyboard.nextInt();
            
                if(userInput == 1) {
                    CreateStudent();
                } else if(userInput == 2) {
                    CreateCourse();
                } else if(userInput == 3) {
                    CreateEnrollment();
                } else if(userInput == 4 ) {
                    EditStudent();
                } else if(userInput == 5) {
                    EditCourse();
                } else if(userInput == 6) {
                    EditEnrollment();
                } else if(userInput == 7) {
                    DisplayStudent();
                } else if(userInput == 8) {
                    DisplayCourse();
                } else if(userInput == 9) {
                    DisplayEnrollment();
                } else if(userInput == 10) {
                    GradesSubMenu();
                } else if(userInput == 0) {
                    System.out.print("Done\n");
                } else {
                    while(userInput > 10) {
                        System.out.println("Invalid Option, Please try again.");
                        userInput = keyboard.nextInt();
                        if(userInput == 1) {
                            CreateStudent();
                        } else if(userInput == 2) {
                            CreateCourse();
                        } else if(userInput == 3) {
                            CreateEnrollment();
                        } else if(userInput == 4 ) {
                            EditStudent();
                        } else if(userInput == 5) {
                            EditCourse();
                        } else if(userInput == 6) {
                            EditEnrollment();
                        } else if(userInput == 7) {
                            DisplayStudent();
                        } else if(userInput == 8) {
                            DisplayCourse();
                        } else if(userInput == 9) {
                            DisplayEnrollment();
                        } else if(userInput == 10) {
                            GradesSubMenu();
                        } else if(userInput == 0) {
                            System.out.print("Done\n");
                        }
                    }
                }
           }
    }
1 Answers

You cannot cast MidTermProject to String, because they are not part of the same class hierarchy.

Serializable is just a marker interface, it does not make it possible to cast string objects to ones that implement serializable.

Ideally what you are looking for is a parser or an object mapper which reads the string input and constructs the deserialized object for you.

Related