定义一个学生类 Student,成员变量包括姓名、性别、年龄、语文成绩、数学成 绩和英语成绩,成员方法包括 getXXX 方法、setXXX 方法、求总分和求平均分。 定义一个测试类 StudentT
时间: 2024-12-19 07:16:57 浏览: 10
好的,下面是一个简单的 Java 类设计,用于定义 `Student` 和 `StudentTest`:
```java
// 定义 Student 类
public class Student {
private String name;
private String gender;
private int age;
private double chineseScore;
private double mathScore;
private double englishScore;
// 构造函数
public Student(String name, String gender, int age, double chineseScore, double mathScore, double englishScore) {
this.name = name;
this.gender = gender;
this.age = age;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
// 获取方法(getters)
public String getName() { return name; }
public String getGender() { return gender; }
public int getAge() { return age; }
public double getChineseScore() { return chineseScore; }
public double getMathScore() { return mathScore; }
public double getEnglishScore() { return englishScore; }
// 设置方法(setters)
public void setName(String name) { this.name = name; }
public void setGender(String gender) { this.gender = gender; }
public void setAge(int age) { this.age = age; }
public void setChineseScore(double chineseScore) { this.chineseScore = chineseScore; }
public void setMathScore(double mathScore) { this.mathScore = mathScore; }
public void setEnglishScore(double englishScore) { this.englishScore = englishScore; }
// 求总分和平均分方法
public double getTotalScore() {
return chineseScore + mathScore + englishScore;
}
public double getAverageScore() {
return getTotalScore() / 3.0;
}
}
// 测试类 StudentTest
public class StudentTest {
public static void main(String[] args) {
// 创建一个学生实例并设置成绩
Student student = new Student("张三", "男", 18, 95.0, 90.0, 85.0);
// 调用方法展示信息
System.out.println("Name: " + student.getName());
System.out.println("Gender: " + student.getGender());
System.out.println("Age: " + student.getAge());
System.out.println("Total Score: " + student.getTotalScore());
System.out.println("Average Score: " + student.getAverageScore());
// 修改成绩并查看更新后的平均分
student.setChineseScore(96.0);
System.out.println("Updated Average Score after raising Chinese score: " + student.getAverageScore());
}
}
```
在这个例子中,我们定义了一个包含个人信息和成绩属性的 `Student` 类,并为其提供了相应的getter和setter方法。同时,还实现了计算总分和平均分的功能。`StudentTest` 类则展示了如何创建 `Student` 的实例,并使用其提供的方法。
阅读全文