Jump to content

Instantiable Classes - Driver Program Error

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Aaron140

Aaron140

    Newbie

  • Members
  • Pip
  • 6 posts
Hello All,

Another Problem.

STUDENTS:


/** A class that models a Student of a driving school

*/



public class Students extends Lessons{


	private String name;

	private String address;

	private int number;

	private int noLessons;



	public Students() {

		name = "No Name Specified";

		address = "No Address Specified";

		number = 0;

		noLessons = 0;

	}



	public Students (String name, String addr, int num, int noLes) {

		setName(name);

		setAddress(addr);

		setNumber(num);

		setNoLessons(noLes);


	}



	public String getName() {

		return name;

	}




    public String getAddress() {

		return address;

	}



    public int getNumber() {

    	return number;

    }



    public int getNoLessons() {

    	return noLessons;

    }




    public void setName(String name) {

    	name = name;

    }




    public void setAddress(String addr) {

    	name = addr;

    }



    public void setNumber(int num) {

    	number = num;

    }



    public void setNoLessons(int noLes) {

    	noLessons = noLes;

    }


    public String toString(){

    	return "Name: " + name + "\nAddress: " + address + "\nPhone Number: " + number + "\nNumber of Lessons: " + noLessons;

    }


}



LESSONS:


/**A class that models the Lessons in a driving school

 */



public class Lessons{

	private String location;

	private String time;

	private double price;


    // 'accessor' methods to return a copy of an attribute

	public String getLocation() { return location;}

	public String getTime() { return time;}

	public double getPrice() { return price;}


	// 'mutator' methods to change the value of an attribute

	public void setLocation (String location) {

				this.location = location;

	}


	public void setTime( String time) {

				this.time = time;

	}


	public void setPrice(double price) {

				this.price = price;

	}


    // 'constructor' methods to give lessons a sensible initial state


	/** full-args constructor, to create a lesson, which everything is known

	 */

	public Lessons(String location, String time, double price) {

				setLocation(location);

				setTime(time);

				setPrice(price);

	}


	/** no-args constructor

	 */

	public Lessons() {

				this("Not Given","00:00",00.00);

	}


	/* String summary of the values of all the object's attributes

	 */

	public String toString() {

				return "Location: " + getLocation() + "\nPrice: €" + getPrice() + "\nTime: " + getTime();

	}

}

DRIVER PROGRAM:


/**Driving School Tester*/


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;


public class DrivingSchoolTest extends JFrame implements ActionListener{

	

	JMenu fileMenu,lessonMenu,studentMenu;

	Students [] student;

	Lessons [] lesson;

	int count;

	int count1;

	

	

	public static void main( String[] args ) {

        DrivingSchoolTest frame = new DrivingSchoolTest();

        frame.setVisible(true);

    }

    

    public DrivingSchoolTest( ) {


        setTitle     ( "Driving School" );

        setSize      ( 400,200 );

        setLocation  ( 350,300 );

        Container pane = getContentPane();

        pane.setBackground(Color.WHITE);

        setDefaultCloseOperation( EXIT_ON_CLOSE );

        

        createFileMenu();

        createStudentMenu();

        createLessonMenu();

        JMenuBar menuBar = new JMenuBar();

        setJMenuBar(menuBar);

        menuBar.add(fileMenu);

        menuBar.add(studentMenu);

        menuBar.add(lessonMenu);

     }

     

     public void newSystemStudent() {

      	student = new Students[10];

      	count = 0;

      }     

    

    

      /** writes the array of students to the file "student.dat"

       */   // NEW


      public void saveStudent() throws IOException {

      	ObjectOutputStream os;

      	os = new ObjectOutputStream(new FileOutputStream ("student.dat"));

      	os.writeObject(student);

      	os.close();

      }

      

       /** loads an array of students from the file "student.dat"

       */  // NEW

      public void openStudent() {

      	count = 0;

      	try{

      	  ObjectInputStream is;

      	  is = new ObjectInputStream(new FileInputStream ("student.dat"));

          student  = (Students []) is.readObject();

      	  is.close();

      	}

      	catch(Exception e){

      		JOptionPane.showMessageDialog(null,"open didn't work");

      		e.printStackTrace();

      	}

      	

      	// how many valid student records?

      	while (student[count] !=null)

      	   count++;

      } // end open()

      

       public void addStudent(){

      	Students s1 = new Students();

      	s1.setName(JOptionPane.showInputDialog("Enter Student Name:"));

      	s1.setAddress(JOptionPane.showInputDialog("Enter address for Student 2: "));

    	s1.setNumber(JOptionPane.showInputDialog("Enter phone number for Student 2: "));

    	s1.setNoLessons(Integer.parseInt(JOptionPane.showInputDialog("Enter number of lessons for Student 2: ")));

      	student[count] = s1; // 'default student

      	// set the attributes: ask the user for name etc

      	count++; // now there is one more student in the system

      }

      

      public void displayStudent(){

      	JTextArea area = new JTextArea();

      	if (count>0) {

      	  area.setText("Student List:");

      	  for (int i = 0; i<count; i++) // loop over existing bikes, rather than array size

      	    area.append("Students: " + i + " " +student[i].toString()+"\n");

      	  showMessage(area);

      	}

      	else

      	    showMessage("No students in the system");

      } // end display

      

      

      

      

      

      

      

       public void newSystemLesson() {

      	lesson = new Lessons[10];

      	count1 = 0;

      }   

      	

      /** writes the array of lessons to the file "lesson.dat"

       */   // NEW

      public void saveLesson() throws IOException {

      	ObjectOutputStream os;

      	os = new ObjectOutputStream(new FileOutputStream ("lesson.dat"));

      	os.writeObject(lesson);

      	os.close();

      }

      

      /** loads an array of lessons from the file "lesson.dat"

       */  // NEW

      public void openLesson() {

      	count1 = 0;

      	try{

      	  ObjectInputStream is;

      	  is = new ObjectInputStream(new FileInputStream ("lesson.dat"));

          lesson  = (Lessons []) is.readObject();

      	  is.close();

      	}

      	catch(Exception e){

      		JOptionPane.showMessageDialog(null,"open didn't work");

      		e.printStackTrace();

      	}

      	

      	// how many valid lesson records?

      	while (lesson[count1] !=null)

      	   count1++;

      } // end open()   

      

      

      public void addLesson(){

      	Lessons l2 = new Lessons();

      	l2.setLocation(JOptionPane.showInputDialog("Enter location for Lesson 2: "));

    	l2.setTime(JOptionPane.showInputDialog("Enter time for Lesson 2: "));

    	l2.setPrice(Double.parseDouble(JOptionPane.showInputDialog("Please enter a price for lesson 2: ")));

      	lesson[count1] = l2; // 'default lesson

      	// set the attributes: ask the user for location etc

      	count++; // now there is one more lesson in the system

      }

      

      public void displayLesson(){

      	JTextArea area = new JTextArea();

      	if (count1>0) {

      	  area.setText("Lesson List:");

      	  for (int i = 0; i<count1; i++) // loop over existing bikes, rather than array size

      	    area.append("Lessons: " + i + " " +lesson[i].toString()+"\n");

      	  showMessage(area);

      	}

      	else

      	    showMessage("No lessons in the system");

      } // end display

      

      

      public void actionPerformed (ActionEvent e) {

      	if (e.getActionCommand() .equals ("Quit")){

      	 showMessage("Shutting down the system");

      	 System.exit(0);

      	}

      	else if (e.getActionCommand() .equals ("Add")){

      	   addStudent(); // branch to a separate method

      	}

      	else if (e.getActionCommand() .equals ("Display")){

           displayStudent();

      	}

      	else if (e.getActionCommand() .equals ("Add")){

      	   addLesson(); // branch to a separate method

      	}

      	else if (e.getActionCommand() .equals ("Display")){

           displayLesson();

      	}

      	else if (e.getActionCommand() .equals ("New File")){

      		newSystemStudent();

      		newSystemStudent();

        }

      	else if (e.getActionCommand() .equals ("Save")){

      	// Error Handling

      	 try{

      	 	saveStudent();

      	 	saveLesson();

      	 	showMessage("Data saved successfully");

      	 } // try

      	 catch (IOException f){

      	 	showMessage("Not able to save the file:");

      	 	f.printStackTrace();

      	 }// catch

      	}// else if

      	

      	else if (e.getActionCommand() .equals ("Open")){

      	 openStudent();

      	 openLesson();

         displayStudent();

         displayLesson();

      	}

      	else

      	  showMessage("Error");

      } // actionPerformed

      

        private void createFileMenu(){

         // create the menu

      	fileMenu = new JMenu("File");

      	// declare a menu item (re-usable)

      	JMenuItem item;

      	item = new JMenuItem("Save");

      	item.addActionListener(this);

      	fileMenu.add(item);

      	item = new JMenuItem("Open");

      	item.addActionListener(this);

      	fileMenu.add(item);

      	item = new JMenuItem("New File");

      	item.addActionListener(this);

      	fileMenu.add(item);

      	// create the 'quit' option

      	fileMenu.addSeparator();

      	item = new JMenuItem("Quit");

      	item.addActionListener(this);

      	fileMenu.add(item);

      }

      

      private void createStudentMenu(){

      	// create the menu

      	studentMenu = new JMenu("Student");

      	// declare a menu item (re-usable)

      	JMenuItem item;

      	

      	item = new JMenuItem("Add");

      	item.addActionListener(this);

      	studentMenu.add(item);

      	

      	item = new JMenuItem("Display");

      	item.addActionListener(this);

      	studentMenu.add(item);

      }

      

      private void createLessonMenu(){

      	// create the menu

      	lessonMenu = new JMenu("Lesson");

      	// declare a menu item (re-usable)

      	JMenuItem item;

      	

      	item = new JMenuItem("Add");

      	item.addActionListener(this);

      	lessonMenu.add(item);

      	

      	item = new JMenuItem("Display");

      	item.addActionListener(this);

      	lessonMenu.add(item);

      }

       /** utility methods to make the code simpler */

      public void showMessage (String s){

      	JOptionPane.showMessageDialog(null,s);

      }

      

      public void showMessage (JTextArea s){

      	JOptionPane.showMessageDialog(null,s);

      }

}


This program compiles Perfectly no errors. My problem is that when i try and add new student the program crashes and i get this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

	at DrivingSchoolTest.addStudent(DrivingSchoolTest.java:83)

	at DrivingSchoolTest.actionPerformed(DrivingSchoolTest.java:170)

	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)

	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)

	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)

	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)

	at javax.swing.AbstractButton.doClick(AbstractButton.java:357)

	at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1170)

	at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1211)

	at java.awt.Component.processMouseEvent(Component.java:6038)

	at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)

	at java.awt.Component.processEvent(Component.java:5803)

	at java.awt.Container.processEvent(Container.java:2058)

	at java.awt.Component.dispatchEventImpl(Component.java:4410)

	at java.awt.Container.dispatchEventImpl(Container.java:2116)

	at java.awt.Component.dispatchEvent(Component.java:4240)

	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)

	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)

	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)

	at java.awt.Container.dispatchEventImpl(Container.java:2102)

	at java.awt.Window.dispatchEventImpl(Window.java:2429)

	at java.awt.Component.dispatchEvent(Component.java:4240)

	at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)

	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)

	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)

	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)

	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)

	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)

	at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Can somebody help with a solution to this and possibly straighten out my code to make it run better.

Thanks for any help.

Aaron.

#2
Vladimir

Vladimir

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Students [] student;
is null (you got java.lang.NullPointerException). As I see from your code, you initialize variable student in newSystemStudent() method, which is called with New File command. So I guess you called Add student without calling New File command.

#3
perfectpitcher22

perfectpitcher22

    Newbie

  • Members
  • Pip
  • 1 posts
I suggest you try having different names for the menu Items. this is a very simple solution.

Else you can find the parent of the menuItem and then decide whether to add a Student or a Lesson.


JMenu parentMenu = null;

        JMenuItem selectedMenuItem = null;


        if (e.getSource() instanceof JMenuItem) {

            selectedMenuItem = (JMenuItem) e.getSource();

        }


        if (selectedMenuItem != null) {

            Component invoker = ((JPopupMenu) selectedMenuItem.getParent()).getInvoker();

            if (invoker instanceof JMenu) {

                parentMenu = (JMenu) invoker;

            }

        }


        if ((parentMenu != null) && (selectedMenuItem != null)) {

            if ((parentMenu.getText().trim().equals("Student")) && (selectedMenuItem.getText().trim().equals("Add"))) {

                System.out.println("Add a Student");

            }

            else if ((parentMenu.getText().trim().equals("Lesson")) && (selectedMenuItem.getText().trim().equals("Add"))) {

                System.out.println("Add a Lesson");

            }

        }


_________________
program errors

Edited by perfectpitcher22, 23 January 2011 - 06:58 AM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users