Reputation: 13
I writing a class and a program for generating quiz average for a specific student.
I'm not sure if I have an error in the main class or in the StudentClass one but every time I run the program, both values it prints out are 0.
Can anyone see an issue with the code that would cause this? This is the main class:
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);
}
}
This is the 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;
}
}
Upvotes: 1
Views: 41
Reputation: 13545
you placed the "total += score;" in the wrong method. consequently, the internal values inside your student class is never updated.
remember to initialize your class.
I've added some comments in the codes.
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;
}
Upvotes: 1
Reputation: 328
The method addQuiz doesn't appear to do anything with the score (such as add it to the total).
getTotalScore() seems to be confused about what 'score' is as well. I wouldn't think you'd want a 'total' type method to add to any member/field, but rather just return the total.
Untested, but try:
public int addQuiz(int score){
numberQuizzes++;
total += score;
return score;
}
public int getTotalScore(){
return total;
}
Upvotes: 1
Reputation: 58882
You need to add quiz scroe inside addQuiz
instead of getTotalScore
method. Move this line:
total += score;
This way you will calculate total every quiz added.
Upvotes: 2