Question 4-1

Consider the following class SemesterEnrollment to represent the enrollments of students in a semester.

public class SemesterEnrollment {
    private int num_students;
    private String[] names;
    private int[] total_enrolled;

    public SemesterEnrollment(int max_students) {
        num_students = 0;
        names = new String[max_students];
        total_enrolled = new int[max_students];
    }

    public void enroll(String name, int credits) {
        for(int i = 0; i < num_students; i++) {
            if(names[i].equals(name)) {
                total_enrolled[i] += credits;
                return;
            }
        }
        names[num_students] = name;
        total_enrolled[num_students] = credits;
        num_students++;
    }

    public int getCreditsTaken(String name) {
        for(int i = 0; i < num_students; i++) {
            if(names[i].equals(name)) {
                return total_enrolled[i];
            }
        }
        return 0;
    }
}
Write another class Registrar containing the single class method run(), which when executed interfaces with the user to enter and query the number of credits enrolled in by various students. This method should be able to handle up to 100 different students. Here is a sample description of how your program should work.
What to do? add Alice 2
What to do? add Bob 4
What to do? add Alice 4
What to do? add Spot 5
What to do? add Bob 1
What to do? query Bob
5
What to do? query Alice
6
  : (This program continues asking questions indefinitely)
Your Registrar class must use the Enrollments class to track the information for each student.

Solution

import csbsju.cs160.*;

public class Registrar {
    public static void run() {
        SemesterEnrollment data = new SemesterEnrollment(100);
        while(true) {
            IO.print("What to do? ");
            String op = IO.readString();

            if(op.equals("add")) {
                String who = IO.readString();
                int how_many = IO.readInt();
                data.enroll(who, how_many);
            } else if(op.equals("query")) {
                String who = IO.readString();
                IO.println(data.getCreditsTaken(who));
            }
        }
    }
}

Back to Review for Quiz 4