Java方法错误且经常重复输出

时间:2015-05-29 06:04:59

标签: java output static-methods repeat

我只是想根据课程导师对StackOverflow的建议获得建议。对不起。

5 个答案:

答案 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);
  }
}

或者,你可以创建一个方法来找到&#34;有该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);
}