java - 在哪里添加java类的成员

标签 java class object

实现一个学生类。出于本练习的目的,学生有一个姓名和总测验分数。提供适当的构造函数和方法 getName() , addQuiz(int score) , getTotalScore() ,和getAverageScore() 。要计算后者,您还需要存储学生参加的测验数量。

...

我对分数和名字感到特别困难。我是否将分数添加到 Student.javaStudentTester.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/

相关文章:

php - 用数组附加 protected 对象

关于引用方法和变量的 Java 约定

java - 如何从服务器(应用程序引擎)获取日期对象并将其转换为客户端的时区日期(获取)?

java - 构造函数 Vehicle(String[], int) 未定义

java - 类图和管理员权限

java - 使用基类实例化派生类有什么好处? java

javascript - 通过在javascript中传递键和值从数组中获取对象

java - 扫描仪类跳过空白

java - NoClassDefFoundError : android. support.v7.internal.view.menu.MenuBuilder

java - Cassandra:将复合主键与batch_mutate java一起使用