java程序统计5位学生成绩,平均分,排名
时间: 2024-10-14 18:02:05 浏览: 28
在Java程序中,统计五位学生的成绩、平均分以及排名可以按照以下步骤完成:
1. 首先,创建一个`Student`类,包含姓名和成绩属性,以及构造函数、getter和setter方法:
```java
public class Student {
private String name;
private double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
// getters and setters...
}
```
2. 然后,你可以创建一个`StudentList`类,用于存储并管理学生列表:
```java
import java.util.ArrayList;
import java.util.Collections;
public class StudentList {
private ArrayList<Student> students;
public StudentList() {
this.students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
// 添加获取平均分和排名的方法
public double calculateAverageScore() {
double sum = 0;
for (Student student : students) {
sum += student.getScore();
}
return sum / students.size();
}
public int rankStudents() {
Collections.sort(students, Comparator.comparingDouble(Student::getScore).reversed());
int rank = 1;
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getScore() == students.get(0).getScore()) {
rank++;
while (i + 1 < students.size() && students.get(i + 1).getScore() == students.get(0).getScore()) {
rank++;
i++;
}
} else {
break;
}
}
return rank;
}
}
```
3. 最后,在主程序中实例化`StudentList`,添加学生,然后计算平均分和排名:
```java
public static void main(String[] args) {
StudentList studentList = new StudentList();
studentList.addStudent(new Student("学生A", 85));
studentList.addStudent(new Student("学生B", 92));
studentList.addStudent(new Student("学生C", 78));
studentList.addStudent(new Student("学生D", 90));
studentList.addStudent(new Student("学生E", 88));
double averageScore = studentList.calculateAverageScore();
int ranking = studentList.rankStudents();
System.out.println("平均分: " + averageScore);
System.out.println("排名最高的学生: " + studentList.students.get(0).getName() + ", 分数: " + studentList.students.get(0).getScore() + ", 排名: " + ranking);
}
```
在这个例子中,程序会输出每个学生的平均分和排名第一的学生信息。
阅读全文