The last example showed a Vector of Vectors, but what if we had more information for the student than just the list of marks, and what if we had more information for the course than just the list of students? It makes sense to make a Student class and a Course class that each have a Vector as a member (instance variable).
Let's suppose we have a Student class that stores each student's marks as a Vector containing Integers:
In lecture, I added an instance variable called "private String name" to store a student's name, and I explained that you'd probably also want to add a constructor that would be used to initialize this name member.
class Student { public void addMark (int i) { marks.addElement(new Integer(i)); } public double getAverage () { if (marks.size() == 0) // Why? return ((double) 0/ 0); double sum = 0; Enumeration e = marks.elements(); while (e.hasMoreElements()) sum += ((Integer)e.nextElement()).intValue(); return sum/marks.size(); } // instantiated before construction private Vector marks = new Vector(); }
That's an ordinary use of Vectors, but now let's suppose we have a course consisting of many students:
In lecture, I added an instance variable called "private String name" to store a course's name, and I explained that you'd probably also want to add a constructor that would be used to initialize this name member.
class Course { public void addStudent (Student s) { students.addElement(s); } // Print average mark for each student public double printMarks () { Enumeration e = students.elements(); while (e.hasMoreElements()) { Student s = (Student)e.nextElement(); System.out.println(s.getName() + ": " + s.getAverage()); } } // instantiated before construction private Vector students = new Vector(); }
We have a Vector of Students, with each Student containing a Vector of Integer marks. It's kind of a "Vector of Vectors" here, but it's "decorated."
How would we use these classes?
Create some student objects:
Student s0 = new Student(); Student s1 = new Student(); Student s2 = new Student();
Let's make a lecture section of students:
Course course = new Course(); course.addStudent(s0); course.addStudent(s1); course.addStudent(s2);
Suppose the first student has three marks: 65, 89 and 47.
s0.addMark(65); s0.addMark(89); s0.addMark(47); … repeat to add several marks for each student …
Print average marks for all students:
course.printMarks();
[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]
© Copyright 2000. All Rights Reserved.