定义一个学生类Student,成员变量包括姓名、性别、年龄、语文成绩、数学成绩和英语成绩,成员方法包括getXXX方法、setXXX方法、求总和、求平均分。根据类Student的定义,创建5个该类的对象,输出每个学生的信息,计算并输出这5个学生成绩的总分和平均值。
时间: 2024-11-22 11:40:54 浏览: 22
在Java中,我们可以按照以下步骤定义一个`Student`类,并完成所需的功能:
```java
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;
}
// getXXX方法
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;
}
// setXXX方法
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() {
if (chineseScore + mathScore + englishScore != 0) {
return (totalScore / 3);
} else {
return 0; // 防止除数为零的情况
}
}
// 主要用于演示,打印学生信息
@Override
public String toString() {
return "Name: " + name + ", Gender: " + gender + ", Age: " + age +
", Chinese Score: " + chineseScore + ", Math Score: " + mathScore +
", English Score: " + englishScore + ", Total Score: " + getTotalScore() +
", Average Score: " + getAverageScore();
}
}
// 创建并操作5个Student对象
public static void main(String[] args) {
Student student1 = new Student("张三", "男", 18, 90, 85, 95);
Student student2 = new Student("李四", "女", 17, 88, 90, 92);
Student student3 = new Student("王五", "男", 16, 92, 88, 93);
Student student4 = new Student("赵六", "女", 19, 95, 89, 90);
Student student5 = new Student("孙七", "男", 17, 90, 92, 88);
System.out.println("Students information:");
System.out.println(student1);
System.out.println(student2);
System.out.println(student3);
System.out.println(student4);
System.out.println(student5);
double totalScore = student1.getTotalScore() + student2.getTotalScore() + student3.getTotalScore() +
student4.getTotalScore() + student5.getTotalScore();
double averageScore = (totalScore / 5);
System.out.println("\nTotal scores: " + totalScore);
System.out.println("Average score: " + averageScore);
}
```
当运行这个`main`函数时,它会创建五个`Student`对象,并分别输出他们的信息以及所有学生的总分和平均分。
阅读全文