我正在创建一个创建类Student的程序。获取名称和总测验分数,添加测验分数,并获得平均测验分数。
public class Student
{
private final String name;
private int totalQuizScore;
public Student(String studentName, int initialScore) //Constructor Students name and total score
{
name = studentName;
totalQuizScore = initialScore;
}
//returns the name of new Student
public String getName()
{
return name;
}
//adds a quiz score to the total quiz scores
public int addQuiz(int score)
{
totalQuizScore = totalQuizScore + score;
return totalQuizScore;
}
//returns the total quiz score
public int getTotalScore()
{
return totalQuizScore;
}
}
这是我的主要
public class StudentGrade {
public static void main(String[] args)
{
Student tim = new Student("Johnson, Tim", 0); //new Student with name Tim Johnson, Initial Score of 0;
tim.getName(); //returns name
tim.addQuiz(9); //add quiz score of 9
tim.addQuiz(10); //add quiz score of 10
tim.addQuiz(10); //add quiz score of 10
tim.getTotalScore();//returns total of all the scores
String name = tim.getName(); //save Student name to variable name
int totalScore = tim.getTotalScore(); //save Student total quiz scores in variable totalScore
System.out.println(name + " " + totalScore);
}
}
我需要计算添加的quizes的平均分数。所以要做到这一点,我需要能够计算添加了多少个测验......这就是我遇到的一些问题。
答案 0 :(得分:0)
创建一个变量count
,每次调用addQuiz()
;
private int count; //initialize to 0 in constructor
public int addQuiz(int score)
{
totalQuizScore = totalQuizScore + score;
++count;
return totalQuizScore;
}
现在计算平均值是将totalQuizScore
除以count
的一个小问题。
答案 1 :(得分:0)
我能想到的最简单的方法是添加(Student
)quizCount
和getQuizAverage()
这样的方法,
private final String name;
private int totalQuizScore;
private int quizCount = 0;
public int addQuiz(int score) {
totalQuizScore += score;
quizCount++;
return totalQuizScore;
}
public float getQuizAverage() {
return ((float)totalQuizScore/quizCount);
}