求解JAVA,定义一个课程类和一个学生类和测试类

2024年11月27日 12:53
有1个网友回答
网友(1):

package arraylist;

public class Course
{

private String name;
private double score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public double getScore()
{
return score;
}
public void setScore(double score)
{
this.score = score;
}

}
package arraylist;

public class Student
{

private String name;
private Course[] scores;
private double average;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}

public Course[] getScores()
{
return scores;
}
public void setScores(Course[] scores)
{
this.scores = scores;
}
public double getAverage()
{
return average;
}
public void setAverage(double average)
{
this.average = average;
}

public void display(){
System.out.println("学生的姓名是" + this.getName() + ".");
for(int i = 0; i < scores.length; i++){
System.out.println("第" + (i + 1) + "门课程的名称是 " + scores[i].getName() + ",成绩是" + scores[i].getScore());
}
System.out.println("学生" + this.getName() +"的平均成绩是" + this.getAverage());
}

public void calAverage(){

double sum = 0;
for(int i = 0; i< scores.length; i++){
sum += scores[i].getScore();
}

this.setAverage(sum/scores.length);
}

public void changeGrade(int i, int score){
scores[i].setScore(score);
}

}
package arraylist;

public class TestDemo
{

public static void main(String[] args){
Student stu = new Student();
stu.setName("小明");
Course[] scores = new Course[3];
scores[0] = new Course();
scores[0].setName("英语");
scores[0].setScore(90);
scores[1] = new Course();
scores[1].setName("语文");
scores[1].setScore(99);
scores[2] = new Course();
scores[2].setName("数学");
scores[2].setScore(80);
stu.setScores(scores);
stu.calAverage();
stu.display();
stu.changeGrade(1, 90);

stu.display();
}
}