// ClassList.java
// This file contains code to partially implement the ClassList class described
// in the lecture for week 7 of CS 1713 Section 2
//
// This class holds an array of StudentGrade objects, allowing the client
// to add students as well as query and change grades.

public class ClassList {

	// this array will hold object references for each student

	StudentGrade[] listOfStudents; 

	// this is the current number of students represented in the array

	int numberOfStudents;

	// constructor

	public ClassList () {

		// allocate an initial array of size 10

		listOfStudents = new StudentGrade[10];

		// initially there are no students

		numberOfStudents = 0;
	}

	// add a student to the list
	
	public void addStudent (StudentGrade s) {

		// if increasing the current number of students would
		// go beyond the bounds of the array...
		if (numberOfStudents >= listOfStudents.length) {

			// ...make a new array and copy the old array into it

			StudentGrade[] aux = new StudentGrade[listOfStudents.length * 2];
			for (int i=0; i<numberOfStudents; i++) aux[i] = listOfStudents[i];

			// now listOfStudents is the new array; the old array
			// will be garbage collected.

			listOfStudents = aux;
		}

		// put the new student into the next available position

		listOfStudents[numberOfStudents] = s;

		// one more student

		numberOfStudents++;
	}
	
	// This method looks up a student by his or her student ID, then
	// returns the grade.  If the ID does not exist, -1 is returned

	public double findGrade (String ID) {

		// find the index of the student by the ID

		int i = lookup (ID);

		// return the grade if it exists, -1 otherwise

		if (i != -1)
			return listOfStudents[i].getGrade();
		else
			return -1.0;
	}
	
	// This method changes a student's grade, returning false if
	// the student's ID can't be found

	public boolean changeGrade (String ID, double grade) {

		// find the index of the student by the ID

		int i = lookup (ID);

		// if the ID exists, change the grade and return true

		if (i != -1) {
			listOfStudents[i].setGrade (grade);
			return true;
		} else {
			return false;
		}
	}
	
	// This private helper method looks up a student's ID and returns
	// the index in the array of the student, or -1 if the ID is not found
	int lookup (String ID) {

		// go through the array looking for the ID

		for (int i=0; i<numberOfStudents; i++)

			// if we find the ID, return this index

			if (listOfStudents[i].getStudentID().equals (ID)) 
				return i;

		// if we make it through the entire loop without returning,
		// then we could not find the ID

		return -1;
	}
		
	// This method converts the ClassList object into a string

	public String toString () {

		// get an empty string

		String r = new String();

		// concatenate each StudentGrade's toString() value to
		// the string, along with a newline

		for (int i=0; i<numberOfStudents; i++)
			r = r + listOfStudents[i].toString() + "\n";
		return r;
	}
}
