Next: None. Up: for loops. Previous: The for loop.


Exercise

Define a class called Student to represent the grade achieved by a student. You'll want the class to employ two instance variables - one to represent how many points the student has earned, and one to represent the total number of points scored so far.

The class should define the following two methods.

void addScore(int score, int possible)
Registers that the student has scored score points out of a possible possible.

double getGrade()
Prints the fraction of points the student has earned. (Returning 1.0 indicates the student has a perfect 100%.)

You can use the following class definition to test your class.

import csbsju.cs160.*;

public class TestStudent {
    public static void run() {
        Student stud = new Student();

        while(true) {
            IO.print("Option (0 for help)? ");
            int option = IO.readInt();

            if(option == 0) {
                IO.println("0   Print this help summary");
                IO.println("1   Add a normal score");
                IO.println("2   Print the student's percentage");
                IO.println("3   Quit program");
            } else if(option == 1) {
                IO.print("Score? ");
                int score = IO.readInt();
                IO.print("Possible? ");
                int possible = IO.readInt();

                stud.addScore(score, possible);
            } else if(option == 2) {
                IO.print("Total is ");
                IO.print(100.0 * stud.getGrade());
                IO.println("%\n");
            } else if(option == 3) {
                break;
            } else {
                IO.println("Invalid option. Press 'h' for help.");
            }
        }
    }
}

An example run of this program:

Option (0 for help)? 1
Score? 23
Possible? 30
Option (0 for help)? 1
Score? 7
Possible? 7
Option (0 for help)? 2
Total is 75.0%
Option (0 for help)? 3


Next: None. Up: for loops. Previous: The for loop.