定义一个Student类,包含如下内容: 成员变量: 学号,姓名,性别,班干部否,数学,语文,外语 成员方法: 输入,总分,平均分 编程实现这个类,并调用相应的方法输入数据,计算总分和平均分。 java
时间: 2024-10-16 20:16:10 浏览: 45
在Java中,你可以创建一个`Student`类来表示学生的基本信息和相关的操作。以下是这个类的定义:
```java
public class Student {
// 成员变量
private String id;
private String name;
private String gender;
private boolean isClassLeader;
private int mathScore;
private int chineseScore;
private int foreignLanguageScore;
// 构造函数
public Student(String id, String name, String gender, boolean isClassLeader) {
this.id = id;
this.name = name;
this.gender = gender;
this.isClassLeader = isClassLeader;
this.mathScore = 0;
this.chineseScore = 0;
this.foreignLanguageScore = 0;
}
// 成员方法
// 输入分数
public void inputScores(int math, int chinese, int foreign) {
this.mathScore = math;
this.chineseScore = chinese;
this.foreignLanguageScore = foreign;
}
// 计算总分
public int getTotalScore() {
return mathScore + chineseScore + foreignLanguageScore;
}
// 计算平均分
public double getAverageScore() {
if (getTotalScore() == 0) {
return 0.0;
}
return (double) getTotalScore() / 3.0;
}
// 获取学生信息的字符串表示
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", isClassLeader=" + isClassLeader +
", mathScore=" + mathScore +
", chineseScore=" + chineseScore +
", foreignLanguageScore=" + foreignLanguageScore +
'}';
}
}
```
接下来,你可以创建一个`main`方法来实例化`Student`并调用它的方法:
```java
public static void main(String[] args) {
// 创建一个学生对象
Student student = new Student("001", "张三", "男", false);
// 输入分数
student.inputScores(85, 90, 92);
// 输出学生信息
System.out.println(student);
// 计算总分和平均分
int totalScore = student.getTotalScore();
double averageScore = student.getAverageScore();
System.out.println("总分:" + totalScore);
System.out.println("平均分:" + averageScore);
}
```
阅读全文