Work with classes: The Student class
Here is a program that solves one of the practice problems
for the final exam. (Answers to question in boldface.)
// Student.java: a simple class holding information about a student
public class Student {
private String name; // In the form "LastName, FirstName"
private double GPA; // grade point average
private int collegeClass; // 1 = FR, 2 = SO, 3 = JR, 4 = SR, 5 = GR
public Student(String n, double gpa, int c) { // constructor
name = n; GPA = gpa; collegeClass = c;
}
public double getGPA() { // return the GPA
return GPA;
}
public String toString() {
return "Name: " + name + ", GPA: " + GPA +
", Class Code: " + collegeClass;
}
}
// Students.java: test the Student class
public class Students {
public static void main (String[] args) {
Student jBlow = new Student("Blow, Joe", 3.4, 2);
Student bBonkers = new Student("Bonkers, Bruce", 2.9, 3);
Student nNutcase = new Student("Nutcase, Nancy", 3.7, 2);
System.out.println(jBlow + "\n" + bBonkers + "\n" + nNutcase);
System.out.println("GPA of JoeBlow: " + jBlow.getGPA());
}
}
The output:
Name: Blow, Joe, GPA: 3.4, Class Code: 2
Name: Bonkers, Bruce, GPA: 2.9, Class Code: 3
Name: Nutcase, Nancy, GPA: 3.7, Class Code: 2
GPA of JoeBlow: 3.4