CS 1063, Fall 2005
|
The lectures for Week 6 had you work on a Student class. Here is one version of that class. Important parts are in red.
public class Student {
private String myName; // Student's name
private int myNumQuizzes; // Number of quizzes
private int myTotalQuizScore; // Sum of quiz scores
public Student(String name) {
// new student, with name, but no quizzes
myName = name;
myNumQuizzes = 0;
myTotalQuizScore = 0;
}
public Student() { // just for fun
this("John Doe");
}
public String getName() {
// return the student's name
return myName;
}
public int getTotal() {
// return the total scores on all quizzes taken
return myTotalQuizScore;
}
public int getNumQuizzes() {
// return the number of quizzes taken
return myNumQuizzes;
}
public void addQuiz(int score) {
// record a new quiz
myTotalQuizScore = myTotalQuizScore + score;
myNumQuizzes++;
}
public double getAverageScore() {
// calculate average quiz grade
if (myNumQuizzes == 0) return 0.0;
else
return (double)myTotalQuizScore/
(double)myNumQuizzes;
}
public String toString() {
// return all the data as a string
return "Name: " + myName +
"\n # quizzes: " + getNumQuizzes() +
"\n Total Quiz Score: " + myTotalQuizScore +
"\n Average Score: " + getAverageScore();
}
}
|
public class StudentTest {
public static void main(String[] args) {
Student noName = new Student();
System.out.println(noName);
Student s1 = new Student("Frank Griswold");
s1.addQuiz(18);
s1.addQuiz(20);
s1.addQuiz(16);
System.out.println(s1);
Student s2 = new Student("Sarah Conner");
System.out.println(s2);
}
}
Output:
Name: John Doe
# quizzes: 0
Total Quiz Score: 0
Average Score: 0.0
Name: Frank Griswold
# quizzes: 3
Total Quiz Score: 54
Average Score: 18.0
Name: Sarah Conner
# quizzes: 0
Total Quiz Score: 0
Average Score: 0.0
|