方法getHomeworkSum()返回最新的作业值,而不是总和

时间:2013-10-19 21:36:49

标签: java methods

有两个班级。 1级有方法。 class 2调用方法。我将向你展示我需要帮助的第1课的部分,但是它将包括整个2级,因为它比2级短得多。

第1课

public void setHomeworkSum() {
        homeworkSum =+ homeworkScore;
    }

    public int getHomeworkSum() {
        return homeworkSum;
    }

第2课

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;


 public class CourseGrade {

public static void main(String[] args) {


    Student myStudent = new Student();


    myStudent.openFile();

    myStudent.setNumberOfStudents();

    System.out.format("%-10s %25s %15s %10s", "Name", "Assignment score", "Test score", "Grade\n");
    System.out.println();

    for(int i = 1; i <= myStudent.getNumberOfStudents(); i++){

    myStudent.setDefault();

    myStudent.setFirstName();

    myStudent.setLastName();

    myStudent.setHomeworkScore();

    myStudent.setTestScore();

    myStudent.setHomeworkScore();

    myStudent.setTestScore();

    myStudent.computeGrade();


    System.out.format("%-19s %1s %21s %13s", myStudent.getFirstName() + " " +      myStudent.getLastName(), myStudent.getHomeworkScore(), myStudent.getTestScore(), myStudent.getGrade() +"\n");

    myStudent.setPassFail();

    myStudent.setHomeworkSum();

    }

    System.out.println();
    System.out.println("No. of students passed: " + myStudent.getPass());
    System.out.println();
    System.out.println("No. of students failed: " + myStudent.getFail());
    System.out.println();
    System.out.println("sum: " + myStudent.getHomeworkSum());

}

}

基本上,我遇到的问题是它不返回所有homeworkscores的总和,而是返回已读取的最新单个homeworkscore。

Output:

Name                Assignment score      Test score     Grade

Anthony Hopkins     854                   284            G
John Smith          730                   214            A
Pan Mei             730                   267            A
Rafael Vega         801                   236            A

No. of students passed: 4

No. of students failed: 0

mean 801

(顶部没有正确转换,但你明白了。)

1 个答案:

答案 0 :(得分:4)

更改为

homeworkSum += homeworkScore;

你有

homeworkSum =+ homeworkScore;

,如果你放一些空间,基本上就是

homeworkSum = +homeworkScore;

因此您始终将最后一个值分配给变量。