我只是想根据课程导师对StackOverflow的建议获得建议。对不起。
答案 0 :(得分:3)
/**
* prints a student’s average grade by student ID
* @param (String studentID)/ */
public static void print_average_grade(String studentID)
{
// Here, you have studentID passed into the function but you are not using it
for (Student s : studentList)
{
// Use the studentID here!
if(s.getStudentID().equals(studentID)) {
double total = s.getGrade1() + s.getGrade2() + s.getGrade3();
double average = total / 3;
System.out.println("StudentID# " + studentID + " " + average);
}
}
}
使用传入的studentID
作为参数,这样您每次都会打印出正确学生的平均成绩。
答案 1 :(得分:3)
你正在使用两个循环,首先使用
for (Student s : studentList) {
print_average_grade(s.getStudentID());
}
调用print_average_grade
,将studentID
传递给你,你会立即忽略它,然后再次遍历所有学生......
public static void print_average_grade(String studentID) {
for (Student s : studentList) {
double total = s.getGrade1() + s.getGrade2() + s.getGrade3();
double average = total / 3;
System.out.println("StudentID# " + studentID + " " + average);
}
}
相反,更改您的print_average_grade
方法以接受Student
并简单计算所述学生的平均值
public static void print_average_grade(Student s) {
double total = s.getGrade1() + s.getGrade2() + s.getGrade3();
double average = total / 3;
System.out.println("StudentID# " + studentID + " " + average);
}
然后在你的主循环中,只需传递你想要的Student
......
for (Student s : studentList) {
print_average_grade(s);
}
如果您“确实”需要id
执行此操作,那么我会编写一个方法,该方法采用int
值(id)并执行查找传回Student
对象,因为你似乎想要这样做几次......(请注意,Map
会更有用)
public Student getStudentById(int id) {
Student match = null;
for (Student s : studentList) {
if (s.getStudentID() == id) {
match = s;
break;
}
}
return match;
}
答案 2 :(得分:1)
在打印平均方法中,您没有使用传递给它的学生ID来过滤列表。您正在迭代整个列表并且每次都打印平均值。但是在打印时,正在使用传递给函数的学生ID,并且所有学生的平均值将以相同的ID显示。
答案 3 :(得分:1)
在print_average_grade
中,包装逻辑以计算平均值,并在条件下打印,只有当s
的学生ID与studentId
匹配时才会执行此操作。
public static void print_average_grade(String studentID) {
for (Student s : studentList) {
if (!s.getStudentID().equals(studentID)) continue;
double total = s.getGrade1() + s.getGrade2() + s.getGrade3();
double average = total / 3;
System.out.println("StudentID# " + studentID + " " + average);
}
}
或者,你可以创建一个方法来找到"有该ID的学生,然后将该学生传递给print_average_grade
。或者,您可以将学生存储在Map<String, Student>
,其中密钥是学生ID,因此您可以找到map.get(studentID)
的学生。
答案 4 :(得分:0)
将print_average_grade(String studentID)更改为print_average_grade(学生)将解决如下问题:
for (Student s : studentList)
print_average_grade(s);
public static void print_average_grade(Student student) {
double total = student.getGrade1() + student.getGrade2()
+ student.getGrade3();
double average = total / 3;
System.out.println("StudentID# " + student.getStudentID() + " "
+ average);
}