Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8816983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T04:44:35+00:00 2026-06-14T04:44:35+00:00

here is my application. I’m having a problem saving objects and opening them. When

  • 0

here is my application. I’m having a problem saving objects and opening them. When I try to save it tells me the variable in the save.writeObject(firstName) cannot be resolved to a variable.

The problem is in the ActionPeformed block:

 import java.awt.*;
 import java.awt.event.*;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
  import java.io.Serializable;

 import javax.swing.*;
 import javax.swing.event.*;
 import javax.swing.border.*;
 import java.util.*;

  public class ClassRoomFrameTest 
{ 
public static void main(String[] args) 
{
    ClassRoomFrame frame = new ClassRoomFrame();
    frame.setSize(600,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
}
} 
class ClassRoomFrame extends JFrame implements ActionListener
{
private JPanel mainPanel = new JPanel();
private JPanel deptPanel = new JPanel(new GridLayout(2,3));
private JPanel studentPanel = new JPanel(new GridLayout(2,5));
private JPanel displayPanel = new JPanel(new BorderLayout());
    private JPanel buttonPanel  = new JPanel(new GridLayout(1,2));
    private JPanel menuBar = new JPanel();

private JTextArea  textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane(textArea);

private JLabel classLocationLabel = new JLabel("Class Location");
private JLabel classRoomLabel     = new JLabel("Class Room Number");
private JLabel classCapacityLabel = new JLabel("Class Capacity");
private JTextField classLocationField = new JTextField();
private JTextField classRoomField     = new JTextField();
private JTextField classCapacityField = new JTextField();

private JLabel studentFNameLabel = new JLabel("First name");
private JLabel studentLNameLabel = new JLabel("Last name");
private JLabel studentIDLabel = new JLabel("ID Number");
private JLabel studentMajorLabel = new JLabel("Major");
private JLabel studentCreditsLabel = new JLabel("Credits");
private JTextField studentFNameField = new JTextField();
private JTextField studentLNameField = new JTextField();
private JTextField studentIDField = new JTextField();
private JTextField studentMajorField = new JTextField();
private JTextField studentCreditsField = new JTextField();

private JButton addButton     = new JButton("Add");
private JButton displayButton = new JButton("Display");

private JMenuBar menu = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem save = new JMenuItem("Open");
private JMenuItem open = new JMenuItem("Save");

private JFileChooser chooser = new JFileChooser();

Classroom room = null;


public ClassRoomFrame()
{
    deptPanel.setPreferredSize(new Dimension(600,50));
    deptPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));

    deptPanel.add(classLocationLabel);
    deptPanel.add(classRoomLabel);
    deptPanel.add(classCapacityLabel);
    deptPanel.add(classLocationField);
    deptPanel.add(classRoomField);
    deptPanel.add(classCapacityField);

    fileMenu.add(fileMenu);
    fileMenu.add(open);
    fileMenu.add(save);

    menu.add(fileMenu);

    studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
    studentPanel.setPreferredSize(new Dimension(600,50));
    studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));

    studentPanel.add(studentFNameLabel);
    studentPanel.add(studentLNameLabel);
    studentPanel.add(studentIDLabel);
    studentPanel.add(studentMajorLabel);
    studentPanel.add(studentCreditsLabel);
    studentPanel.add(studentFNameField);
    studentPanel.add(studentLNameField);
    studentPanel.add(studentIDField);
    studentPanel.add(studentMajorField);
    studentPanel.add(studentCreditsField);

    scrollPane.setBorder(new BevelBorder(BevelBorder.LOWERED));
    scrollPane.setPreferredSize(new Dimension(600,450));
    textArea.setBorder(new EmptyBorder(new Insets(5,15,5,15)));

    buttonPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
    buttonPanel.setPreferredSize(new Dimension(600, 50));
    buttonPanel.add(addButton);
    buttonPanel.add(displayButton);
    addButton.addActionListener(this);
    addButton.setActionCommand("Add");
    displayButton.addActionListener(this);
    displayButton.setActionCommand("Display");

    open.addActionListener(this);
    open.setActionCommand("Open");
    save.addActionListener(this);
    save.setActionCommand("Save");

    mainPanel.add(deptPanel);       
    mainPanel.add(studentPanel);        
    mainPanel.add(scrollPane);


    add(menu, BorderLayout.NORTH);
    add(mainPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);       
}

@SuppressWarnings("unused")
public void actionPerformed(ActionEvent e)
{
    /*---> HERE */if(e.getActionCommand().equals("Save"));
    {
        FileOutputStream saveFile = null;
        ObjectOutputStream save = null;

        try 
        {
            saveFile = new FileOutputStream("ObjectData.txt");
            save = new ObjectOutputStream(saveFile);

            /*--->Error*/ save.writeObject(index);

            save.writeObject(new Classroom());
        } catch (FileNotFoundException e1) 
        {

            e1.printStackTrace();
        } catch (IOException e1) 
        {

            e1.printStackTrace();
        }
        finally
        {
            try {saveFile.close();

            }catch(Exception exc){
                System.out.println(exc.getMessage());
            }
            }       

    }
    /*---> Here*/if (e.getActionCommand().equals("Open"))
    {
        ObjectInputStream in = null;
        int returnVal = chooser.showOpenDialog(ClassRoomFrame.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = chooser.getSelectedFile();
            try {
        in = new ObjectInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e1) 
            {

                e1.printStackTrace();
            } catch (IOException e1) 
            {

                e1.printStackTrace();
            }
        }
            try {
                Student st = (Student)in.readObject();
                Classroom cs = (Classroom)in.readObject();
                System.out.println(st);
                System.out.println(cs);

            } catch (IOException e1) {

                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {

                e1.printStackTrace();
            }
            try{in.close();}
            catch(Exception err){err.getMessage();}
    }

    if(e.getActionCommand().equals("Add"))
    {
        if(room == null)
        {
            room = new Classroom(classLocationField.getText(),
    Integer.parseInt(classRoomField.getText()),
           Integer.parseInt(classCapacityField.getText()));
            room.addStudent(
                   new Student(studentFNameField.getText(),      
                     studentLNameField.getText(),
                     studentIDField.getText(),
                     studentMajorField.getText(),
               Integer.parseInt(studentCreditsField.getText())));

            classLocationField.setEditable(false);
            classRoomField.setEditable(false);
            classCapacityField.setEditable(false);
            studentFNameField.setText("");       
            studentLNameField.setText("");
            studentIDField.setText("");
            studentMajorField.setText("");
                            studentCreditsField.setText("");
            textArea.setText("Class and first student added.");
        }
        else
        {
            room.addStudent(
                   new Student(studentFNameField.getText(),      
                     studentLNameField.getText(),
                     studentIDField.getText(),
                     studentMajorField.getText(),
               Integer.parseInt(studentCreditsField.getText())));
            textArea.setText("Next student added.");

            studentFNameField.setText("");       
            studentLNameField.setText("");
            studentIDField.setText("");
            studentMajorField.setText("");
        studentCreditsField.setText("");
        }           
    }
    else if(e.getActionCommand().equals("Display"))
    {
        if (room != null)
        {
            textArea.setText(room.toString());
        }
        else
        {
            textArea.setText("Nothing to display");
        }   
    }
}
}

class Student implements Serializable
{
public String firstName, lastName, studentIdNumber, studentMajor;
public int totalCourseCredits;

//-----------------------------------------------------------------
// Create an empty studentusing a default constructor.
//-----------------------------------------------------------------
public Student ()
{
}
//-----------------------------------------------------------------
// Creates a Student with the specified information.
//-----------------------------------------------------------------
public Student (String name1, String name2, String identification, 
                String myMajor, int myTotalCredits)
{
    firstName = name1;
    lastName = name2;
    studentIdNumber = identification;
    studentMajor = myMajor;
    totalCourseCredits = myTotalCredits;
}

//-----------------------------------------------------------------
// Gets and sets first name.
//-----------------------------------------------------------------
public void setFirstName()
{
    Scanner scan = new Scanner (System.in);

    System.out.println ("Enter your First Name: ");
    firstName = scan.nextLine();
}

//-----------------------------------------------------------------
// Gets and sets last name.
//-----------------------------------------------------------------
public void setLastName()
{
    Scanner scan = new Scanner (System.in);

    System.out.println ("Enter your Last Name: ");
    lastName = scan.nextLine();
}

//-----------------------------------------------------------------
// Gets and sets Total Course Credits.
//-----------------------------------------------------------------
public void setTotalCredits()
{
    Scanner scan = new Scanner (System.in);

    System.out.println ("Enter your Total Credits: ");
    totalCourseCredits = scan.nextInt();
}

//-----------------------------------------------------------------
// Gets and sets Student ID Number.
//-----------------------------------------------------------------
public void setIdNumber()
{
    Scanner scan = new Scanner (System.in);

    System.out.println ("Enter your ID Number: ");
    studentIdNumber = scan.nextLine();
}


//-----------------------------------------------------------------
// Gets and sets Student Major.
//-----------------------------------------------------------------
public void setMajor()
{
    Scanner scan = new Scanner (System.in);

    System.out.println ("Enter your Major: ");
    studentMajor = scan.nextLine();
}

 public String toString()
 {
    String s = "First name:     " + firstName + "\n" + 
               "Last name:      " + lastName + "\n" + 
               "StudentID:      " + studentIdNumber + "\n" + 
               "Student Major:  " + studentMajor + "\n" + 
                "Course Creidts: " + totalCourseCredits + "\n"; 
    return s;
}
}

   class Classroom implements Serializable
  {

    private Student[] classRoster;
private int index = 0;
    private int capacityStudents, roomNumber;
    private String buildingLocation;

  //-----------------------------------------------------------------
  // Creates an empty Classroom.
  //-----------------------------------------------------------------
public Classroom()
{
    capacityStudents = 0;
  roomNumber = 0;
  buildingLocation = "";
}

  //-----------------------------------------------------------------
  // Creates a Classroom with the specified information.
  //-----------------------------------------------------------------
public Classroom(String location, int room, int cap)
{
    capacityStudents = cap;
  roomNumber = room;
  buildingLocation = location;
  classRoster = new Student[capacityStudents];
}


  //-----------------------------------------------------------------
  // Gets and sets Building Location.
 //-----------------------------------------------------------------
  public void setBuilding()
 {
  Scanner scan = new Scanner (System.in);

  System.out.println ("Enter the Building Location: ");
  buildingLocation = scan.next();
 }

  //-----------------------------------------------------------------
  // Gets and sets Room Number.
  //-----------------------------------------------------------------
public void setRoomNumber()
{
  Scanner scan = new Scanner (System.in);

  System.out.println ("Enter the Room Number: ");
  roomNumber = scan.nextInt();
}

  //-----------------------------------------------------------------
  // Sets Capacity of Students.
  //-----------------------------------------------------------------
public void setCapacityStudents()
{
  Scanner scan = new Scanner (System.in);

  System.out.println ("Enter The Capacity of the Classroom: ");
  capacityStudents = scan.nextInt();
  classRoster = new Student[capacityStudents];
}

  //-----------------------------------------------------------------
  // Gets Capacity of Students.
 //-----------------------------------------------------------------
public int getCapacityStudents()
{
  return capacityStudents;
}

  //-----------------------------------------------------------------
 // Adds an Individual Student to the Classroom, checking if the 
 // capacity of the clasroom is full.
 //-----------------------------------------------------------------
public void addStudent (Student student)
{
    if(index < capacityStudents)
    {
      classRoster[index] = student;
      index++;
    }
    else
    {
      System.out.println("Capacity exceeded! - Student cannot be added.");
    }   
}

 //-----------------------------------------------------------------
 // Adds an Individual Student to the Classroom, checking if the 
 // capacity of the clasroom is full.
 //-----------------------------------------------------------------
  public String toString()
{
    StringBuffer sb = new StringBuffer
                          ("Building:     " + buildingLocation +
                           "\nClass room: " + roomNumber +
                "\nCapacity:   " + capacityStudents + "\n\n"
                                 ); 
    for(int i = 0; i < classRoster.length; i++)
    {
        if(classRoster[i] != null)
          sb.append(classRoster[i].toString() + "\n");
    }
    return sb.toString();
   }
  }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T04:44:36+00:00Added an answer on June 14, 2026 at 4:44 am

    The error is telling you that index is not available in the scope of the save method. You would need to do something like save.writeObject( classroom.getIndex()) in the save method, if you want to save the index.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I try to save the toggle state in my application.Here is my code boolean
Hi i have integrated twitter in my android application.here the problem is when i
I have a jsfiddle application here and I have a problem when it comes
I have a problem on reading data from serial-port in my winform application...here is
as i am facing problem here: Installing application on SD-card in Android sdk 2.2
I have mvc3 application here my problem is on same page i.e on Index.cshtml
hi i am doing one application here i need to disply 6 images in
I have a Jsfiddle application here . If you type in a question in
I've downloaded a sample application sending email silverlight application here. via gmail. But I
From My Previous question sending request to apple - from iphone custom application Here,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.