Reputation: 93
I created a function to identify the maximum value at an array. The function call works only when the array has one item. Can you check the code below and tell me what you think?
Output I receive
The Highest Grade Student is: Grade: 0.0
Output Needed (example)
The Highest Grade Student is: 976 Grade: 90.0
Highest Grade Function:
public static String highestGrade(Student[] d)
{ // the function checks the highest grade and returns the corresponding id
// d is an array of Student data type
double max = d[0].getScore(); // assigning max value for reference
int gradeCounter = 1; // counter
String topID = ""; // emplty string
// looping through array
for( ; gradeCounter< d.length; gradeCounter++ )
{
if( d[gradeCounter].getID() != "")
// Checking if there is an ID assigned
{ // comparing the score at index with the max value
if(d[gradeCounter].getScore() > max)
{ // if the score is higher than the max value, the max is updated
max = d[gradeCounter].getScore();
topID=d[gradeCounter].getID();
}
}
}
return topID; // returning the id that corresponds to the highest grade
}
Print Report Function
public static void printReport(Student[] c)
{
System.out.print("\n ***Class Report*** \n\n");
// Looping through the array and printing both Id and Grade
for(int idCounter = 0; idCounter<c.length; idCounter++ )
{
if( c[idCounter].getID() != "")
{
System.out.print("ID: ");
System.out.print(c[idCounter].getID());
System.out.print(" Grade: ");
System.out.println(c[idCounter].getGrade());
}
}
//*******This is the part that has the issue*************
// providing the user with the id having the highest grade
System.out.print("\nThe Highest Grade Student is: ");
// assigning a variable to the function call of highestgrade id
String studentHighestGrade=highestGrade(c);
// printing the variable to provide the id
System.out.print(studentHighestGrade);
// providing the user with grade that corresponds to the id
System.out.print(" Grade: ");
// declaring and initializing a variable
double valueOfHighestGrade = 0.0;
// Looping through the array to get the highest grade that
// corresponds to the ID
for(int idCounter = 0; idCounter<c.length; idCounter++ )
{
// if the id at index =idCounter equals the highest id then
// we get the grade (score) at that index and assign it to
// valueOfHighestGrade
if(c[idCounter].getID().equals(studentHighestGrade))
{
valueOfHighestGrade=c[idCounter].getScore();
}
}
// printing the highest grade (score)
System.out.print(valueOfHighestGrade);
countGrades( c);
System.out.print("\n ***End of Report*** \n");
}
Upvotes: 0
Views: 57
Reputation: 781
Upvotes: 0
Reputation: 44834
If you only have one Student
in your array,
as you are doing int gradeCounter = 1; // counter
then you will not get the value of the student id,
so before your loop in highestGrade
do
topID = d[0].getId();
Not sure why you are doing if (c[idCounter].getID() != "")
though
Upvotes: 2