构造函数类出错?

时间:2018-05-09 04:21:05

标签: java constructor

我写了一个课程和一个程序,用于为特定学生生成测验平均值。

我不确定主类或StudentClass中是否有错误,但每次运行程序时,打印出的两个值都为0.

任何人都可以看到导致此问题的代码问题吗?这是主要的课程:

public class Student {

public static void main(String[] args) {
    StudentClass quizzes = new StudentClass();

    int[] quizArray = {54, 85, 32, 98, 43, 89};

    quizzes.addQuiz(quizArray[0]);
    quizzes.addQuiz(quizArray[1]);
    quizzes.addQuiz(quizArray[2]);
    quizzes.addQuiz(quizArray[3]);
    quizzes.addQuiz(quizArray[4]);
    quizzes.addQuiz(quizArray[5]);

    int total = quizzes.getTotalScore();
    int average = quizzes.getQuizAverage();

    System.out.println("Total score: " + total);
    System.out.println("Quiz average: " + average);



        }

    }

这是StudentClass:

public class StudentClass {
private String name;
private static int numberQuizzes;
private int average;
private int score;
private int total;

public String getName(String name) {
    return this.name;

}

public int addQuiz(int score){
    numberQuizzes++;
    return score;
}

public int getTotalScore(){
    total += score;
    return total;

}

public int getQuizAverage(){
    average = total / numberQuizzes;
    return average;

}

}

3 个答案:

答案 0 :(得分:1)

您需要在addQuiz而不是getTotalScore方法中添加测验scroe。移动这一行:

 total += score;

这样您就可以计算每次测验的总数。

答案 1 :(得分:1)

你放了“总+ =得分”;在错误的方法。因此,学生班级内部的值永远不会更新。

记得初始化你的班级 我在代码中添加了一些注释。

public class StudentClass {
private String name;
private static int numberQuizzes =0 ; //increment this every time addQuiz is called
// private int average; // you do not need this...you can re-calculate this
// private int score; //you do not need this.
private int total =0 ; //update your total score on addQuiz()

public int addQuiz(int score){
    numberQuizzes++;
    //update the total score everytime addQuiz() is called.
    total+= score; // this line is missing in your codes.

    return score;
}

public int getTotalScore(){
    // total += score; // this line is redundant.
    return total; 
}

public int getQuizAverage(){
    if(numberQuizzes==0) return 0; //prevent div by zero exception

    return total / numberQuizzes; 

}

答案 2 :(得分:0)

方法addQuiz似乎没有对分数做任何事情(例如将其添加到总分中)。

getTotalScore()似乎对什么得分'感到困惑。也是。我不会认为你想要一个全面的'类型方法添加到任何成员/字段,而只是返回总数。

未经测试,但请尝试:

public int addQuiz(int score){
    numberQuizzes++;
    total += score;
    return score;
}

public int getTotalScore(){
    return total;

}