This exercise will give you practice in writing methods that do things with arrays.
You may have some doubts that this is a sensible program. Perhaps it would be a good idea to have the spread() method print out a message each time it is used.
Carefully study how the variable gradeCount works.
It is both the count of how many array slots have data and the
index of the next available array slot.
This is a common programming "trick."
Entire Program, with testing class: You might wish to copy this program to NotePad, save it to a file, and to play with it.
class StudentGrades
{
final int arraySize = 25;
// Instance Variables
String name; // the name of the student
int[] grades; // the array of grades
int gradeCount; // how many of the slots have data
// Constructor
StudentGrades( String studentName )
{
name = studentName ;
grades = new int[ arraySize ] ;
gradeCount = 0 ;
}
// Methods
public void print ()
{
System.out.println ( "Name: " + name );
System.out.println( "Grades:");
for ( int j=0; j < gradeCount ; j++ )
System.out.println ( " grade " + j + ": " + grades[ j ] );
}
public void addGrade ( int grade )
{
if ( gradeCount < arraySize )
grades[gradeCount] = grade ;
gradeCount ++ ;
}
public double average ( )
{
double sum = 0 ;
for ( int j=0; j < gradeCount; j++ )
sum += grades[ j ] ;
return sum / gradeCount ;
}
public int minimum( )
{
int min = grades[ 0 ] ;
for ( int j=0; j < gradeCount; j++ )
if ( grades[j] < min )
min = grades[j] ;
return min ;
}
public int maximum( )
{
int max = grades[ 0 ] ;
for ( int j=0; j < gradeCount; j++ )
if ( grades[j] > max )
max = grades[j] ;
return max ;
}
}
class StudentTester
{
public static void main ( String[] args )
{
// create a student object
StudentGrades stud = new StudentGrades( "Laura Lyons" ) ;
// add a few grades
stud.addGrade( 90 ) ;
stud.addGrade( 95 ) ;
stud.addGrade( 88 ) ;
stud.addGrade( 78 ) ;
stud.addGrade( 82 ) ;
stud.addGrade( 97 ) ;
// print out the object with its new values
stud.print() ;
// compute and print the average, minimum and maximum
System.out.println( "Average grade: " + stud.average() + " Minimum: " + stud.minimum() +
" Maximum: " + stud.maximum() );
}
}