我创建了一个函数来识别数组的最大值。函数调用仅在数组有一个项时有效。你能查看下面的代码并告诉我你的想法吗?
我收到的输出
最高年级学生是:年级:0.0
需要输出(示例)
最高年级学生是:976年级:90.0
最高等级功能:
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
}
打印报告功能
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");
}
答案 0 :(得分:2)
如果您的数组中只有一个Student
,
当你在做int gradeCounter = 1; // counter
时,你将无法获得学生ID的值,
所以在highestGrade
进行循环之前
topID = d[0].getId();
不知道你为什么要做if (c[idCounter].getID() != "")
答案 1 :(得分:0)
使用equals方法比较String实例的建议。
答案 2 :(得分:0)