ITEC 120 LAB 11 Back to Lab index page

Tracking Grades

A teacher wants a program to keep track of grades for students and decides to create a student class for his program as follows:

1) File Student.java contains an incomplete definition for the Student class. Save it to your directory and complete the class definition as follows:

2) File Grades.java contains a shell program that declares two Student objects. Save it to your directory and use the inputGrades method to read in each student's test scores, then use the getAverage method to find their average. Print the average with the student's name, e.g., "The average for Joe is 87." You can use the getName method to print the student's name.

3) Add statements to your Grades program that print the values of your Student variables directly, for example:

System.out.println("Student 1: " + student1);

This should compile, but notice what it does when you run it - nothing very useful! When an object is printed, Java looks for a toString method for that object. This method must have no parameters and must return a String. If such a method has been defined for this object, it is called and the string it returns is printed. Otherwise the default toString method, which is inherited from the Object class, is called; it simply returns a unique hexadecimal identifier for the object such as the ones you saw above.

Add a toString method to your Student class that returns a string containing the student's name and test scores, for example:

Name: Joe     Test1: 85     Test2: 91

Note that the toString method does not call System.out.println - it just returns a string.

Recompile your Student class and the Grades program (you shouldn't have to change the Grades program-you don't have to call toString explicitly). Now see what happens when you print a student object - much nicer!