LAB 33 – Creating Classes (part 2)
Lab Exercises
Topics
n To create accessor and modifier methods.
n To access and process an array
Exercises
11.5 Creating Accessors (Getters) and Modifiers (Setters)
i) Add the following sets and gets to the Student class used in Lab32 [Add the appropriate documentation for each method]
//////////////methods ///////////////
/**
* Method to get the name for this student
* @return the name
*/
public String getName() { return this.name; }
/**
* Method to get the grade at index for this student
* @param index – position of grade to be retrieved
* @return the grade at location index
*/
public double getGrade (int index)
{
return this.gradeArray[index];
}
public boolean setName (String theName)
{
boolean noName = false;
if (this.name == null)
{
this.name = theName;
noName = true;
}
return noName;
}
public boolean setGrade (int index, double newGrade)
{
boolean done = false;
if (this.gradeArray != null && newGrade >= 0)
{
this.gradeArray[index] = newGrade;
done = true;
}
return done;
}
public boolean setGradeArray (double[] theArray)
{
boolean done = false;
if (this.gradeArray == null)
{
this.gradeArray = theArray;
done = true;
}
return done;
}
public double getAverage()
{
double average = 0.0;
if (this.gradeArray != null && this.gradeArray.length > 0)
{
double sum = 0.0;
for (double grade : this.gradeArray)
sum += grade;
average = sum / this.gradeArray.length;
}
return average;
}
a. Ask the user for student1’s grades and use the setGradeArray method to set the grades for student1. Display the new student1. [NOTE: You will need to include “grades = new double[numberOfGrades];” to reset the array of grades]
b. Use get’s and set’s to add 5 points to each of student2’s grades
c. Use getAverage to get the average for the two students and display a message identifying the name of the student with the larger average.
QUESTIONS:
Submit the ProcessStudents.java and Student.java files through the DropBox in WebCT.