实现一个学生类。出于本练习的目的,学生有一个姓名和总测验分数。提供适当的构造函数和方法 getName()
, addQuiz(int score)
, getTotalScore()
,和getAverageScore()
。要计算后者,您还需要存储学生参加的测验数量。
...
我对分数和名字感到特别困难。我是否将分数添加到 Student.java
和 StudentTester.java
文件还是只有测试仪?我无法弄清楚这一点。
这是我的代码:
/** A student has taken a number of quizzes and has an average score
based on the quizzes that were taken.
*/
public class Student
{
private String name;
private double totalscore;
private int numquiz;
}
// Constructs a student object with the name "MccStudent" and with zero total of quiz scores
public Student(String "mccStudent")
{
this.name = studentname;
numquiz = 0;
totalscore = 0;
}
public String getName()
{
return name;
}
// Adds the number of quizzes taken
public void addQuiz(double quizscore)
{
totalscore+=quizscore;
numquiz++;
}
// Returns the total quiz score
public double getTotalScore ()
{
return totalscore;
}
// Returns the avaerage grade
public double getAverageScore ()
{
return totalscore/numquiz;
}
}
/** Create a class to test the Student class.
*/
public class StudentTester
{
/**
Tests the methods of the Student class.
*/
public static void main(String[] args)
{
// Create an object
Student mccStudent = new Student();
mccStudent.addQuiz(100);
mccStudent.addQuiz(80);
mccStudent.addQuiz(95);
mccStudent.addQuiz(97);
System.out.println(mccStudent.getName());
System.out.println(mccStudent.getTotalScore());
// Display average quiz score
System.out.println(mccStudent.getAverage.Score());
}
}
最佳答案
首先尝试了解什么是构造函数。这是带有很好示例的 Oracle 文档:Constructor 。我给你写一个简单的例子。 Student 是具有 String name 属性的新对象。
public class Student {
public String name; //name of student
public Student(String name) {//Constructor for student, receiving name when u create new object Student
this.name = name; //set received name to this public String name
}
/**
* When u call this method you will get inputed name from constructor
* so if u call Student stud = new Student("John");
* new Student("John") is constructor!
* with stud.getName(); you will get "John".
* This is called getter.
* @return name of student
*/
public String getName() {
return name;
}
}
关于java - 在哪里添加java类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670912/