Tracking Grades

This lab gives you practice with using methods to access and change private data members, and also with method overriding. A teacher wants a program to keep track of grades for students and decides to create a student class for her 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:
    1. Declare the instance data (name, score for test1, and score for test2).
    2. Add the missing method headers.
    3. Add the missing method bodies. Scanner may be useful!

  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 printName method to print the student's name.

  3. The printName method is rather cumbersome for producing the output described above. Add a method getName to your Student class that instead of printing the name, returns it as a string. Now modify your Grades program to use getName instead of printName in printing each student's average.

  4. Modify the inputGrades method of the Student class so that it validates the grades it reads in. That is, if a grade entered is less than 0 or greater than 100, it should print a warning message and ask for another grade. This should be repeated (for each grade entered) until the grade is between 0 and 100.

  5. Add statements to your Grades program that print the values of your Student variables directly, e.g.:
        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, e.g.:

                      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!

Go back to lab1 index page