Question

Hi, I need help to finish this program. Thank you import java.io.FileNotFoundException; import javax.swing.JFrame; /** *...

Hi,

I need help to finish this program.

Thank you

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

/**
* The Main class containing the main() and run() methods.
*/
public class Main {
  
public static void main(String[] pArgs) {
   new Main().run();
}


/**
* The Roster of students that is read from the input file "gradebook.dat".
*/
  
???


/**
* A reference to the View object.
*/
???

/**
* This is where execution starts. Instantiate a Main object and then call run().
*/
???

/**
* exit() is called when the Exit button in the View is clicked. When we exit we have to write
* the roster to the output file "gradebook.dat". Then we exit the program with a code of 0.
*
* We open the file and write the roster to it in a try-catch block, where we catch a
* FileNotFoundException that will be thrown if for some reason, we cannot open "gradebook.dat"
* for writing.
*
* PSEUDOCODE:
* method exit() : void
* try
* instantiate a GradebookWriter object named gbWriter, opening "gradebook.dat" for
* writing
* call writeGradebook(getRoster()) on gbWriter
* call System.exit(0) to terminate the application with an exit code of 0
* catch FileNotFoundException e
* call messageBox() on getView() to display a message box containing the text "Could
* not open gradebook.dat for writing. Exiting without saving."
* call System.exit(-1) to terminate the application with an error code of -1
* end try-catch
* end exit
*/
  
private void run(){
   JFrame.setDefaultLookAndFeelDecorated(true);
   setView(new View(this));
   try {
GradebookReader gradeBook = new GradebookReader("gradebook.txt");
setRoster(gradeBook.readGradebook());
mRoster = getRoster();


} catch (FileNotFoundException pException) {
getView().messageBox("Could not open gradebook.txt for reading. Exiting.");
System.exit(-1);
}
}


/**
* This method returns the number of exams in the class.
*/
???

/**
* This method returns the number of homework assignments in the class.
*/
???
  
/**
* Accessor method for mRoster.
*/
private Roster getRoster() {
return mRoster;
}

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

/**
* run() is the main routine and is called from main().
*
* PSEUDOCODE:
* method run
* call JFrame.setDefaultLookAndFeelDecorated(true or false depending on your preference)
* -- Create the View passing 'this' as the argument so the View will be linked to the Main
* -- class so they may communicate with each other. Then pass the newly created View object
* -- to setView() to save the reference to the View in our instance variable mView.
* call setView(new View(this)) to create the View and stored the returned object in mView
* try
* -- Note that when we try to open "gradebook.dat" for reading that GradebookReader()
* -- may throw a FileNotFoundException which we catch here.
* create a GradbookReader object named gbReader opening "gradebook.dat" for reading
* -- Read the student roster from the input file.
* call readGradebook() on gbReader, which returns the Roster
* call setRoster() on the Roster returned from readGradebook() to save the roster in
* our instance variable mRoster
* catch
* call messageBox() on getView() to display the error message "Could not open
* gradebook.dat for reading. Exiting."
* call System.exit(-1) to terminate the application with an exit code of -1
* end try-catch
* end run
*/
  
private void run(){
   JFrame.setDefaultLookAndFeelDecorated(true);
   setView(new View(this));
   try {
GradebookReader gradeBook = new GradebookReader("gradebook.txt");
setRoster(gradeBook.readGradebook());
mRoster = getRoster();


} catch (FileNotFoundException pException) {
getView().messageBox("Could not open gradebook.txt for reading. Exiting.");
System.exit(-1);
}
}


/**
* search() is called when the Search button is clicked in the View. The input parameter is
* the last name of the Student to search the roster for. Call getStudent(pLastName) on the
* Roster object (call getRoster() to get the reference to the Roster) to get a reference to
* the Student with that last name. If the student is not located, getStudent() returns null.
*
* @param pLastName The last name of the student who we will search the Roster for.
*
* PSEUDOCODE:
* method search(pLastName : String) : Student
* call getRoster().getStudent(pLastName) and return what getStudent() returns
* end search
*/
public Student search(String pLastName) {
return getRoster().getStudent(pLastName);
}


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

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Main.java


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 gbWriter = new GradebookWriter("gradebook.txt");
           gbWriter.writeGradebook(getRoster());
           System.exit(0);
           gbWriter.close();
       }
       catch (FileNotFoundException fnfe){
           getView().messageBox("Could not open gradebook.txt for writing. Exiting without saving.");
           System.exit(-1);
       }
    } //END OF exit()

    /**
     * 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(false);
       setView(new View(this));
      
       try{
           GradebookReader gbReader = new GradebookReader("gradebook.txt");
           setRoster(gbReader.readGradebook());
       }
       catch (FileNotFoundException fnfe){
           getView().messageBox("Could not open gradebook.txt for reading. Exiting.");
           System.exit(-1);
       }
    } //END OF run()

    /**
     * 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);
    } //END OF search()

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

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

Roster.java

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 Roster(){
       mStudentList = new ArrayList<Student>();
    }

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

  
    public Student getStudent(String pLastName){
       int index = Searcher.search(getStudentList(), pLastName);
      
       if (index == -1){
           return null;
       }
       else{
           return getStudentList().get(index);
       }
    } //END OF getStudent()

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

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


    public void sortRoster(){
       Sorter.sort(getStudentList());
    }

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

Student.java

import java.util.ArrayList;

/**
* The Student class stores the grade information for one Student.
*/
public class Student implements Comparable<Student> {

    // Declare the instance variables.
    ArrayList<Integer> mExamList;
    ArrayList<Integer> mHomeworkList;
    String mFirstName;
    String mLastName;

    /**
     * Student()
     *
     * PSEUDOCODE:
     * Save pFirstName and pLastName.
     * Create mExamList
     * Create mHomeworkList
     */
     public Student(String pFirstName, String pLastName){
       mFirstName = pFirstName;
       mLastName = pLastName;
       mExamList = new ArrayList<Integer>();
       mHomeworkList = new ArrayList<Integer>();
     } //END OF Student() <<ctor>>

    /**
     * addExam()
     *
     * PSEUDOCODE:
     * Call add(pScore) on getExamList() to add a new exam score to the list of exam scores.
     */
    public void addExam(int pScore){
       getExamList().add(pScore);
    }

    /**
     * addHomework()
     *
     * PSEUDOCODE:
     * Call add(pScore) on getHomeworkList() to add a new homework score to the list of homework scores.
     */
    public void addHomeWork(int pScore){
       getHomeworkList().add(pScore);
    }

    /**
     * compareTo()
     *
     * PSEUDOCODE:
     * Return: -1 if the last name of this Student is < the last name of pStudent
     * Return: 0 if the last name of this Student is = the last name of pStudent
     * Return: 1 if the last name of this Student is > the last name of pStudent
     * Hint: the last names are Strings.
     */
    public int compareTo(Student pStudent){
       return (this.getLastName()).compareTo(pStudent.getLastName());
    }

    /**
     * getExam()
     *
     * Accessor method to retreive an exam score from the list of exams.
     */
    public int getExam(int pNum) {
        return getExamList().get(pNum);
    }

    /**
     * getExamList()
     *
     * Accessor method for mExamList.
     */
    protected ArrayList<Integer> getExamList() {
        return mExamList;
    }

    /**
     * getFirstName()
     *
     * Accessor method for mFirstName.
     */
    public String getFirstName() {
        return mFirstName;
    }

    /**
     * getHomework()
     *
     * Accessor method to retrieve a homework score from the list of homeworks.
     */
    public int getHomework(int pNum) {
        return getHomeworkList().get(pNum);
    }

    /**
     * getHomeworkList()
     *
     * Accessor method for mHomeworkList.
     */
    protected ArrayList<Integer> getHomeworkList() {
        return mHomeworkList;
    }

    /**
     * getLastname()
     *
     * Accessor method for mLastName.
     */
    public String getLastName() {
        return mLastName;
    }

    /**
     * setExam()
     *
     * Mutator method to store an exam score into the list of exam scores.
     */
    public void setExam(int pNum, int pScore) {
        getExamList().set(pNum, pScore);
    }

    /**
     * setExamList()
     *
     * Mutator method for mExamList.
     */
    protected void setExamList(ArrayList<Integer> pExamList) {
        mExamList = pExamList;
    }

    /**
     * setFirstName()
     *
     * Mutator method for mFirstName.
     */
    public void setFirstName(String pFirstName) {
        mFirstName = pFirstName;
    }

    /**
     * setHomework()
     *
     * Mutator method to store a homework score into the list of homework scores.
     */
    public void setHomework(int pNum, int pScore) {
        getHomeworkList().set(pNum, pScore);
    }

    /**
     * setHomeworkList()
     *
     * Mutator method for mHomeworkList.
     */
    protected void setHomeworkList(ArrayList<Integer> pHomeworkList) {
        mHomeworkList = pHomeworkList;
    }

    /**
     * setLastname()
     *
     * Mutator method for mLastName.
     */
    public void setLastName(String pLastName) {
        mLastName = pLastName;
    }

    /**
     * toString()
     *
     * Returns a String representation of this Student. The format of the returned string shall be such that the Student
     * information can be printed to the output file, i.e:
     *
     * lastname firstname hw1 hw2 hw3 hw4 exam1 exam2
     */
    @Override
    public String toString(){
       String str = this.getLastName()+ " " + this.getFirstName() + " ";
      
       for (int i = 0; i < getHomeworkList().size(); i++){
           str += getHomework(i) + " ";
       }
      
       for (int i = 0; i < getExamList().size(); i++){
           str += getExam(i) + " ";
       }
       return str.trim();
    } //END OF toString()
} //END OF Student CLASS

View.java


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 {

    /**
   * Serial version for View
   */
   private static final long serialVersionUID = 1L;
  
   public static final int FRAME_WIDTH = 500;
    public static final int FRAME_HEIGHT = 250;

    // Declare instance variables
    private JButton mClearButton;
    private JTextField[] mExamText;
    private JButton mExitButton;
    private JTextField[] mHomeworkText;
    private Main mMain;
    private JButton mSearchButton;
    private JButton mSaveButton;
    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();
        panelSearch.add(new JLabel("Student Name: "));
        mSearchText = new JTextField(25);
        panelSearch.add(mSearchText);
        mSearchButton = new JButton("Search");
        mSearchButton.addActionListener(this);
        panelSearch.add(mSearchButton);

        // 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: "));
        mHomeworkText = new JTextField[CourseConstants.NUM_HOMEWORKS];
        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: "));
        mExamText = new JTextField[CourseConstants.NUM_EXAMS];
        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);
      
        //----EXTRA: Added this line of code to set the GUI to the middle of the screen---
        setLocationRelativeTo(null);
    } //END OF View() <<ctor>>


    public void actionPerformed(ActionEvent pEvent){
       if (pEvent.getSource() == mSearchButton){
           String lastName = mSearchText.getText();
          
           if (lastName.isEmpty()){
               messageBox("Please enter the student's last name.");
           }
           else{
               mStudent = mMain.search(lastName);
               if (mStudent == null){
                   messageBox("Student not found. Try again.");
               }
               else{
                   displayStudent(mStudent);
               }
           }
       }
       else if (pEvent.getSource() == mSaveButton){
           if (mStudent != null){
               saveStudent(mStudent);
           }
       }
       else if (pEvent.getSource() == mClearButton){
           clear();
       }
       else if (pEvent.getSource() == mExitButton){
           if (mStudent != null){
               saveStudent(mStudent);
           }
           mMain.exit();
       }
    }//END OF actionPerformed()

    /**
     * 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 < mHomeworkText.length; i++){
           mHomeworkText[i].setText("");
       }
       for (int i = 0; i < mExamText.length; i++){
           mExamText[i].setText("");
       }
       mStudent = null;
    } //END OF clear()

    /**
     * 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++){
           int hw = pStudent.getHomework(i);
           String hwstr = Integer.toString(hw);
           mHomeworkText[i].setText(hwstr);
       }
       for (int i = 0; i < CourseConstants.NUM_EXAMS; i++){
           int exam = pStudent.getExam(i);
           String examstr = Integer.toString(exam);
           mExamText[i].setText(examstr);
       }
    }//END OF displayStudent()

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

    /**
     * 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();
           int hw = Integer.parseInt(hwstr);
           pStudent.setHomework(i, hw);
       }
       for (int i = 0; i < CourseConstants.NUM_EXAMS; i++){
           String examstr = mExamText[i].getText();
           int exam = Integer.parseInt(examstr);
           pStudent.setExam(i, exam);
       }
    }//END OF saveStudent()
  
}//END OF View CLASS

CourseConstants.java


public class CourseConstants {

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

}

Searcher.java

import java.util.ArrayList;

public class Searcher{
  
   public static int search(ArrayList<Student> pList, String pKey){
       int low = 0;
       int high = pList.size() - 1;
      
       while (low <= high){
           int middle = (low + high) / 2;
           if (pList.get(middle).getLastName().equalsIgnoreCase(pKey)){
               return middle;
           }
           else if ((pList.get(middle).getLastName()).compareToIgnoreCase(pKey) < 0){
               low = middle + 1;
           }
           else {
               high = middle - 1;
           }
       } //END OF while loop
      
       return -1;
   } //END OF search()
}//END OF Searcher CLASS

Sorter.java

import java.util.ArrayList;
import java.util.Collections;

public class Sorter {
  
   private static int partition(ArrayList<Student> pList, int pFromIdx, int pToIdx){
       Student pivot = pList.get(pFromIdx);
       int leftIndex = pFromIdx - 1;
       int rightIndex = pToIdx + 1;
      
       while(leftIndex < rightIndex){
          
           leftIndex++;
           while (pList.get(leftIndex).compareTo(pivot) < 0){
               leftIndex++;
           }
          
           rightIndex--;
           while(pList.get(rightIndex).compareTo(pivot) > 0){
               rightIndex--;
           }
          
           if (leftIndex < rightIndex){
               swap(pList, leftIndex, rightIndex);
           }
       }//END OF while LOOP
       return rightIndex;
   } //END OF partition()
  
   private static void quickSort(ArrayList<Student> pList, int pFromIdx, int pToIdx){
       if (pFromIdx >= pToIdx){
           return;
       }
      
       int partitionIndex = partition(pList, pFromIdx, pToIdx);
      
       quickSort(pList, pFromIdx, partitionIndex);
       quickSort(pList, partitionIndex + 1, pToIdx);
   } //END OF quickSort()
  
   public static void sort(ArrayList<Student> pList){
       quickSort(pList, 0, pList.size() - 1);
   } //END OF sort()
  
   private static void swap(ArrayList<Student> pList, int pIdx1, int pIdx2){
       Collections.swap(pList, pIdx1, pIdx2);
   } //END of swap()
} //END OF Sorter CLASS

GradebookWriter.java


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 {

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

    /**
     * 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()){
           println(student);
       }
       close();
    }//END OF writeGradebook()
} //END OF GradebookWriter CLASS


GradebookReader.java

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 gradebook 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;
    }
}

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


Add a comment
Know the answer?
Add Answer to:
Hi, I need help to finish this program. Thank you import java.io.FileNotFoundException; import javax.swing.JFrame; /** *...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • Can anyone debug this for me please? Java code to copy package debugmeone; import java.io.File; import...

    Can anyone debug this for me please? Java code to copy package debugmeone; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadTextFile { private Scanner input; // Ignore the hint given by NetBeans public void openFile() { try { input = new Scanner( new File("accountrecords.txt")); } catch(Exception e) { System.out.println("Something bad just happened here."); System.exit(707); } catch( FileNotFoundException fnfe) { System.out.println("Error - File Not Found: accountrecords.txt"); System.exit(100); } } } ITCS-2590 Debugging Execse Chapter 11 - NetBeans IDE 8.2 File...

  • package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public...

    package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public static void main (String [] args)    {    // ============================================================    // Step 2. Declaring Variables You Need    // These constants are used to define 2D array and loop conditions    final int NUM_ROWS = 4;    final int NUM_COLS = 3;            String filename = "Input.txt";    // A String variable used to save the lines read from input...

  • Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person...

    Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person and Student represent individuals with a first and last name as String class variables, and Student has an additional int class variable that represents a ID number. The Roster class represents a group of people that are objects of either the Person or Student class. It contains an ArrayList. The Person class has been completed for you with class variables, a constructor, and a...

  • Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException;...

    Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BSTTreeNode{    BSTTreeNode left, right;    String data; public BSTTreeNode(){    left = null;    right = null;    data = null; } public BSTTreeNode(String n){    left = null;    right = null;    data = n; } public void setLeft(BSTTreeNode n){    left = n; } public void setRight(BSTTreeNode n){   ...

  • Java Programming Reading from a Text File Write a Java program that will use an object...

    Java Programming Reading from a Text File Write a Java program that will use an object of the Scanner class to read employee payroll data from a text file The Text file payroll.dat has the following: 100 Washington Marx Jung Darwin George 40 200 300 400 Kar Car Charles 50 22.532 15 30 The order of the data and its types stored in the file are as follows: Data EmployeelD Last name FirstName HoursWorked double HourlyRate Data Tvpe String String...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • JAVA program Note: you can't change anything is already written Student.java public class Student {   ...

    JAVA program Note: you can't change anything is already written Student.java public class Student {    private String name;    private String major;    private double gpa;    public Student(String name, String major, double gpa) {        // TO-DO: Assign the given parameters to the data fields. Use the this keyword.    }    public double getGPA() {        // TO-DO: return this.gpa    }    public String getName() {        // TO-DO: return this.name    }...

  • I want to extend this GUI application in java language. Thanks for the help in advance. import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.Action...

    I want to extend this GUI application in java language. Thanks for the help in advance. import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FormWindow {     private JFrame frame;     /**      * Launch the application.      */     public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 try {                     FormWindow window = new FormWindow();                     window.frame.setVisible(true);                 } catch (Exception e) {                     e.printStackTrace();                 }             }         });     }     /**      * Create the application.      */     public FormWindow() {         initialize();    ...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT