Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I\'m having problems here, and I\'m not sure what I\'m doing wrong. I\'m pret

ID: 3749342 • Letter: S

Question

So I'm having problems here, and I'm not sure what I'm doing wrong. I'm pretty sure my error is in my GUI but, could you look it over and see what I'm doing wrong?  

Here are the errors:

run:

Exception in thread "main" java.lang.NullPointerException

at p03.Roster.addStudent(Roster.java:35)

at p03.GradebookReader.readRoster(GradebookReader.java:72)

at p03.GradebookReader.readGradebook(GradebookReader.java:46)

at p03.Main.run(Main.java:86)

at p03.Main.main(Main.java:29)

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

at p03.Main.search(Main.java:102)

at p03.View.actionPerformed(View.java:150)

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

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

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

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

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

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

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

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

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

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

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

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

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

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

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

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

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

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

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.awt.EventQueue$4.run(EventQueue.java:729)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

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

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

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

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

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

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

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

BUILD SUCCESSFUL (total time: 1 minute 0 seconds)

Main:

//***************************************************************************************************************************
// CLASS: Main
//
// AUTHOR
// Your author information
//***************************************************************************************************************************
package p03;

import java.io.FileNotFoundException;
import javax.swing.JFrame;

/**
* The Main class containing the main() and run() methods.
*/
public class Main {

// The Roster of students that is read from "gradebook.txt".
private Roster mRoster;

// A reference to the View object.
private View mView;

/**
* This is where execution starts. Instantiate a Main object and then call
* run().
*/
public static void main(String[] pArgs) {
Main main = new Main();
main.run();
}

/**
* exit() is called when the Exit button in the View is clicked.
*
* PSEUDOCODE: try Instantiate a GradebookWriter object opening
* "gradebook.txt" for writing Call writeGradebook(getRoster()) on the
* object Call System.exit(0) to terminate the application catch
* FileNotFoundException Call messageBox() on the View to display ""Could
* not open gradebook.txt for writing. Exiting without saving." Call
* System.exit(-1) to terminate the application with an error code of -1
*/
public void exit() {
try {
GradebookWriter writer = new GradebookWriter("gradebook.txt");
writer.writeGradebook(getRoster());
System.exit(0);
} catch (FileNotFoundException pExcept) {
getView().messageBox("Could not open gradebook.txt for writing."
+ "Exit without saving.");
System.exit(-1);
}
}

/**
* Accessor method for mRoster.
*/
public Roster getRoster() {
return mRoster;
}

/**
* Accessor method for mView.
*/
public View getView() {
return mView;
}

/**
* run() is the main routine.
*
* PSEUDOCODE: Call JFrame.setDefaultLookAndFeelDecorated(true or false
* depending on your preference) Call setView(instantiate new View object
* passing this to the ctor) try Instantiate a GradebookReader object to
* open "gradebook.txt" for reading Call readGradebook() on the object Call
* setRoster() to save the Roster returned from readGradebook() catch Call
* messageBox() on the View to display "Could not open gradebook.txt for
* reading. Exiting." Call System.exit(-1) to terminate the application with
* an error code
*/
private void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
setView(new View(this));

try {
GradebookReader reader = new GradebookReader("gradebook.txt");
setRoster(reader.readGradebook());
} catch (FileNotFoundException pExcept) {
getView().messageBox("Could not open gradebook.txt for reading. "
+ "Exiting.");
System.exit(-1);
}
}

/**
* search() is called when the Search button is clicked on the View. The
* input parameter is the non-empty last name of the Student to locate. Call
* getStudent(pLastName) on the Roster object to get a reference to the
* Student with that last name. If the student is not located, getStudent()
* returns null.
*/
public Student search(String pLastName) {
return getRoster().getStudent(pLastName);
}

/**
* Mutator method for mRoster.
*/
public void setRoster(Roster pRoster) {
mRoster = pRoster;
}

/**
* Mutator method for mView.
*/
public void setView(View pView) {
mView = pView;
}
}

Roster:

//***************************************************************************************************************************
// CLASS: Roster
//
// AUTHOR
// Your author information
//***************************************************************************************************************************
package p03;

import java.util.ArrayList;

/**
* The Roster class encapsulates an ArrayList<Student> which stores the
* information for each student in the gradebook.
*/
public class Roster {

// Declare mStudentList
ArrayList<Student> mStudentList;

/**
* Roster()
*
* PSEUDOCODE: Create mStudentList.
*/
public void Roster() {
mStudentList = new ArrayList<Student>();
}

/**
* addStudent()
*
* PSEUDOCODE: Add (append) pStudent to mStudentList.
*/
public void addStudent(Student pStudent) {
mStudentList.add(pStudent);
}

/**
* getStudent() Searches mStudentList for a Student with pLastName.
*
* PSEUDOCODE: index = Call Searcher.search(getStudentList(), pLastName) If
* index == -1 Then Return null Else return the Student object in
* mStudentList at index
*/
public Student getStudent(String pLastName) {
int index = Searcher.search(getStudentList(), pLastName);
if (index == -1) {
return null;
} else {
return getStudentList().get(index);
}
}

/**
* getStudentList() Accessor method for mStudentList.
*/
public ArrayList<Student> getStudentList() {
return mStudentList;
}

/**
* setStudentList() Mutator method for mStudentList.
*/
public void setStudentList(ArrayList<Student> pStudentList) {
mStudentList = pStudentList;
}

/**
* sortRoster() Called to sort the roster by last name.
*
* PSEUDOCODE: Call Sorter.sort() passing the list of students
*/
public void sortRoster() {
Sorter.sort(mStudentList);
}

/**
* Returns a String representation of this Roster. Handy for debugging.
*/
@Override
public String toString() {
String result = "";
for (Student student : getStudentList()) {
result += student + " ";
}
return result;
}
}

Sorter:

/*
//********************************************************************************************************
// CLASS: classname (classname.java)
//
// DESCRIPTION
// A description of the contents of this file.
//
// COURSE AND PROJECT INFO
// CSE205 Object Oriented Programming and Data Structures, semester and year
// Project Number: project-number
//
// AUTHOR
// your-name (your-email-addr)
//********************************************************************************************************

*/
package p03;

import java.util.ArrayList;

/**
*
* @author thndr
*/
public class Sorter {

//implement the quicksort algorithm
private static int partition(ArrayList<Student> pList, int pFromldx, int pToldx) {
Student pivot = pList.get(pFromldx);

int leftIndex = pFromldx - 1;
int rightIndex = pToldx + 1;

while (leftIndex < rightIndex) {
leftIndex++;
while (pList.get(leftIndex).compareTo(pivot) == -1) {
leftIndex++;
}
rightIndex--;
while (pList.get(rightIndex).compareTo(pivot) == 1) {
rightIndex--;
}
if (leftIndex < rightIndex) {
swap(pList, leftIndex, rightIndex);
}
}
return rightIndex;
}

private static void quickSort(ArrayList<Student> pList, int pFromldx, int pToldx) {
if (pFromldx < pToldx) {
int partitionIndex = partition(pList, pFromldx, pToldx);
quickSort(pList, pFromldx, partitionIndex);
quickSort(pList, partitionIndex + 1, pToldx);
}
}

//Entry point for sorter
public static void sort(ArrayList<Student> pList) {
quickSort(pList, 0, pList.size() - 1);
}

private static void swap(ArrayList<Student> pList, int pldx1, int pldx2) {
Student temp = pList.get(pldx1);
pList.set(pldx1, pList.get(pldx2));
pList.set(pldx2, temp);
}
}

View

//***************************************************************************************************************************
// CLASS: View
//
// AUTHOR
// Your author information
//***************************************************************************************************************************
package p03;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
* The View class implements the GUI.
*/
public class View extends JFrame implements ActionListener {

public static final int FRAME_WIDTH = 500;
public static final int FRAME_HEIGHT = 250;

// Declare instance variables
private JButton mClearButton;
private JTextField[] mExamText = new JTextField[CourseConstants.NUM_EXAMS];
private JButton mExitButton;
private JTextField[] mHomeworkText = new JTextField[CourseConstants.NUM_HOMEWORKS];
private JButton mSaveButton;
private JButton mSearchButton;
private Main mMain;
private JTextField mSearchText;
private Student mStudent;

/**
* View()
*
* The View constructor creates the GUI interface and makes the frame
* visible at the end.
*/
public View(Main pMain) {
// Save a reference to the Main object pMain in mMain.
mMain = pMain;

JPanel panelSearch = new JPanel();
mSearchText = new JTextField(25);
panelSearch.add(mSearchText);
mSearchButton = new JButton("Search");
mSearchButton.addActionListener(this);
panelSearch.add(mSearchButton);
// PSEUDOCODE:
// Create a JPanel named panelSearch which uses the FlowLayout.
// Add a JLabel "Student Name: " to panelSearch
// Create mSearchText and make the field 25 cols wide
// Add mSearchText to the panel
// Create mSearchButton
// Make this View the action listener for the button
// Add the button to the panel

// PSEUDOCODE:
// Create a JPanel named panelHomework which uses the FlowLayout.
// Add a JLabel "Homework: " to the panel
// Create mHomeworkText which is an array of CourseConstants.NUM_HOMEWORKS JTextFields
// For i = 0 to CourseConstants.NUM_HOMEWORKS - 1 Do
// Create textfield mHomeworkText[i] displaying 5 cols
// Add mHomeworkText[i] to the panel
// End For
JPanel panelHomework = new JPanel();
panelHomework.add(new JLabel("Homework"));
for (int i = 0; i < CourseConstants.NUM_HOMEWORKS; ++i) {
mHomeworkText[i] = new JTextField(5);
panelHomework.add(mHomeworkText[i]);
}
// Create the exam panel which contains the "Exam: " label and the two exam text fields. The pseudocode is omitted
// because this code is very similar to the code that creates the panelHomework panel.
JPanel panelExam = new JPanel();
panelExam.add(new JLabel("Exam: "));
for (int i = 0; i < CourseConstants.NUM_EXAMS; ++i) {
mExamText[i] = new JTextField(5);
panelExam.add(mExamText[i]);
}
// PSEUDOCODE:
// Create a JPanel named panelButtons using FlowLayout.
// Create the Clear button mClearButton.
// Make this View the action listener for mClearButton.
// Add the Clear button to the panel.
// Repeat the three above statements for the Save button.
// Repeat the three above statements for the Exit button.
JPanel panelButtons = new JPanel();
mClearButton = new JButton("Clear");
mClearButton.addActionListener(this);
panelButtons.add(mClearButton);
mSaveButton = new JButton("Save");
mSaveButton.addActionListener(this);
panelButtons.add(mSaveButton);
mExitButton = new JButton("Exit");
mExitButton.addActionListener(this);
panelButtons.add(mExitButton);

// PSEUDOCODE:
// Create a JPanel named panelMain using a vertical BoxLayout.
// Add panelSearch to panelMain.
// Add panelHomework to panelMain.
// Add panelExam to panelMain.
// Add panelButtons to panelMain.
JPanel panelMain = new JPanel();
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS));
panelMain.add(panelSearch);
panelMain.add(panelHomework);
panelMain.add(panelExam);
panelMain.add(panelButtons);
// Initialize the remainder of the frame, add the main panel to the frame, and make the frame visible.
setTitle("Gradebookulator");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panelMain);
setVisible(true);
}

/**
* actionPerformed()
*
* Called when one of the JButtons is clicked. Detects which button was
* clicked and handles it.
*
* PSEUDOCOODE: If the source of the event was the Search button Then
* lastName = retrieve the text from the mSearchText text field. If lastName
* is the empty string Then Call messageBox() to display "Please enter the
* student's last name." Else student = Call mMain.search(lastName) If
* student is null Then Call messageBox() to display "Student not found. Try
* again." Else Call displayStudent(student) End if End If Else if the
* source of the event was the Save button Then If mStudent is not null Then
* Call saveStudent(mStudent) Else if the source of the event was the Clear
* button Then Call clear() Else if the source of the event was the Exit
* button Then If mStudent is not null Then Call saveStudent(mStudent) Call
* mMain.exit() to terminate the application End If
*/
@Override
public void actionPerformed(ActionEvent pEvent) {
switch (pEvent.getActionCommand()) {
case "Search":
String lastName = mSearchText.getText();
if (lastName.isEmpty()) {
this.messageBox("Please enter the student's last name");
} else {
Student student = mMain.search(lastName);
if (student == null) {
this.messageBox("Student not found, try again.");
} else {
mStudent = student;
displayStudent(student);
}
}
break;
case "Save":
if (mStudent != null) {
saveStudent(mStudent);
}
mMain.exit();
break;
}
}

/**
* clear()
*
* Called when the Clear button is clicked. Clears all of the text fields by
* setting the contents to the empty string. After clear() returns, no
* student information is being edited or displayed.
*
* PSEUDOCODE: Set the mSearchText text field to "" Set each of the homework
* text fields to "" Set each of the exam text fields to "" Set the mStudent
* reference to null
*/
private void clear() {
mSearchText.setText("");
for (int i = 0; i < CourseConstants.NUM_HOMEWORKS; ++i) {
mHomeworkText[i].setText("");
}
for (int i = 0; i < CourseConstants.NUM_EXAMS; ++i) {
mExamText[i].setText("");
}
mStudent = null;
}

/**
* displayStudent()
*
* Displays the homework and exam scores for a student in the mHomeworkText
* and mExamText text fields.
*
* PSEUDOCODE: For i = 0 to CourseConstants.NUM_HOMEWORKS - 1 Do int hw =
* pStudent.getHomework(i) String hwstr = convert hw to a String (Hint:
* Integer.toString()) mHomeworkText[i].setText(hwstr) End For Write another
* for loop similar to the one above to place the exams scores into the text
* fields
*/
private void displayStudent(Student pStudent) {
for (int i = 0; i < CourseConstants.NUM_HOMEWORKS; ++i) {
Integer hw = pStudent.getHomework(i);
String hwStr = hw.toString();
mHomeworkText[i].setText(hwStr);
}
for (int i = 0; i < CourseConstants.NUM_EXAMS; ++i) {
Integer exam1 = pStudent.getExam(i);
String exam1Str = exam1.toString();
mExamText[i].setText(exam1Str);
}
}

/**
* messageBox()
*
* Displays a message box containing some text.
*/
public void messageBox(String pMessage) {
JOptionPane.showMessageDialog(this, pMessage, "Message", JOptionPane.PLAIN_MESSAGE);
}

/**
* saveStudent()
*
* Retrieves the homework and exam scores for pStudent from the text fields
* and writes the results to the Student record in the Roster.
*
* PSEUDOCODE: For i = 0 to CourseConstants.NUM_HOMEWORKS - 1 Do String
* hwstr = mHomeworkText[i].getText() int hw = convert hwstr to an int
* (Hint: Integer.parseInt()) Call pStudent.setHomework(i, hw) End For Write
* another for loop similar to the one above to save the exam scores
*/
private void saveStudent(Student pStudent) {
for (int i = 0; i < CourseConstants.NUM_HOMEWORKS; ++i) {
String hwStr = mHomeworkText[i].getText();
Integer hw = Integer.parseInt(hwStr);
pStudent.setHomework(i, hw);
}
for (int i = 0; i < CourseConstants.NUM_EXAMS; ++i) {
String examsStr = mExamText[i].getText();
Integer exam = Integer.parseInt(examsStr);
pStudent.setExam(i, exam);
}
int studentdx = Searcher.search(mMain.getRoster().getStudentList(),
pStudent.getLastName());
mMain.getRoster().getStudentList().set(studentdx, pStudent);
}

}

Searcher

/*
//********************************************************************************************************
// CLASS: classname (classname.java)
//
// DESCRIPTION
// A description of the contents of this file.
//
// COURSE AND PROJECT INFO
// CSE205 Object Oriented Programming and Data Structures, semester and year
// Project Number: project-number
//
// AUTHOR
// your-name (your-email-addr)
//********************************************************************************************************

*/
package p03;

import java.util.ArrayList;

/**
*
* @author thndr
*/
public class Searcher {

//implement binary search algorithm (loop or recursive)
public static int search(ArrayList<Student> studentList, String pKey) {

//loop to search and match last name
for (int i = 0; i < studentList.size(); i++) {
Student std = studentList.get(i);
if (pKey.equalsIgnoreCase(std.getLastName()))//if statement to compare pKey to current array list
{
return i;//return back index back to caller
}
}
return -1;//return -1 if name doesn't exist
}

}

Course Contants

//***************************************************************************************************************************
// CLASS: CourseConstants
//
// AUTHOR
// Your author information
//***************************************************************************************************************************
package p03;

public class CourseConstants {

public static final int NUM_EXAMS = 2;
public static final int NUM_HOMEWORKS = 4;

}

GradebookReader

//***************************************************************************************************************************
// CLASS: GradebookReader
//
// AUTHOR
// Kevin R. Burger (burgerk@asu.edu)
// Computer Science & Engineering Program
// Fulton Schools of Engineering
// Arizona State University, Tempe, AZ 85287-8809
//***************************************************************************************************************************
package p03;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
* GradebookRead reads the gradebook info from the file name passed to the ctor.
*/
public class GradebookReader {

private Scanner mIn;

/**
* Attempts to open the dgradebook file for reading. If successful, mIn will
* be used to read from the file. If the file cannot be opened, a
* FileNotFoundException will be thrown.
*/
public GradebookReader(String pFname) throws FileNotFoundException {
mIn = new Scanner(new File(pFname));
}

/**
* Reads the exam scores for a Student.
*/
private void readExam(Student pStudent) {
for (int n = 0; n < CourseConstants.NUM_EXAMS; ++n) {
pStudent.addExam(mIn.nextInt());
}
}

/**
* Called to read the gradebook information. Calls readRoster() to read the
* student records and then sorts the roster by last name.
*/
public Roster readGradebook() {
Roster roster = readRoster();
roster.sortRoster();
return roster;
}

/**
* Reads the homework scores for a Student.
*/
private void readHomework(Student pStudent) {
for (int n = 0; n < CourseConstants.NUM_HOMEWORKS; ++n) {
pStudent.addHomework(mIn.nextInt());
}
}

/**
* Reads the student information from the input file adding Student objecs
* to the roster.
*/
private Roster readRoster() {
Roster roster = new Roster();
while (mIn.hasNext()) {
String lastName = mIn.next();
String firstName = mIn.next();
Student student = new Student(firstName, lastName);
readHomework(student);
readExam(student);
roster.addStudent(student);
}
return roster;
}
}

GradebookWriter

//***************************************************************************************************************************
// CLASS: GradebookWriter
//
// AUTHOR
// Your author information
//***************************************************************************************************************************
package p03;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
* GradebookWriter inherits from PrintWriter and writes the gradebook info to
* the file name passed to the ctor.
*/
public class GradebookWriter extends PrintWriter {

private PrintWriter mOut;

/**
* GradebookWriter() Call the super class ctor that takes a String.
*/
public GradebookWriter(String pFname) throws FileNotFoundException {
super(new File(pFname));
mOut = this;
}

/**
* writeGradebook() Writes the gradebook info to the file, which was opened
* in the ctor.
*
* PSEUDOCODE: EnhancedFor each student in pRoster.getStudentList() Do Call
* println(student) End For Call close()
*/
public void writeGradebook(Roster pRoster) {
for (Student student : pRoster.getStudentList()) {
mOut.println(student);
}
mOut.close();
}
}

gradebook.txt

Simpson Lisa 25 25 25 25 100 100
Flintstone Fred 15 17 22 18 80 60
Jetson George 20 21 22 23 70 83
Explosion Nathan 5 4 3 2 1 0
Muntz Nelson 20 15 10 5 60 70
Terwilliger Robert 23 21 19 17 80 90
Flanders Ned 12 14 17 23 85 95
Bouvier Selma 16 16 16 16 16 16
Spuckler Cletus 1 2 3 4 5 6
Wiggum Clancy 6 5 4 3 2 1
Skinner Seymour 19 23 21 24 78 83

Explanation / Answer

I have found the issue, but I'm not able to test it completely at my end, beacse you haven't shared Student class.

You can fix this error on your own, let me first explain why you are getting this error, This is because you haven;'t defined default constructor inside the Roster.java i.e.

public Roster() {

mStudentList = new ArrayList<Student>();

}

What you did wrong in Roster.java, you wrote it with a return type void like written below-

public void Roster() {

mStudentList = new ArrayList<Student>();

}

So please just go into your Roster.java file and remove the void keyword, it will work fine, if if need more assistance leave your comment, I would be happy to assist you more on this problem.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote