三十个学生姓名,学号,四门成绩随机产生,成绩存入数组中,存入一个对象数组,再求全班平均分并随机输出一个同学的成绩 JAVA
时间: 2024-05-27 20:12:07 浏览: 145
import java.util.Random;
public class Student {
private String name; // 学生姓名
private int id; // 学号
private int[] scores = new int[4]; // 四门成绩
public Student(String name, int id) {
this.name = name;
this.id = id;
// 随机生成四门成绩
Random random = new Random();
for (int i = 0; i < scores.length; i++) {
scores[i] = random.nextInt(101);
}
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public int[] getScores() {
return scores;
}
public double getAverageScore() {
int sum = 0;
for (int score : scores) {
sum += score;
}
return sum / (double) scores.length;
}
public static void main(String[] args) {
Student[] students = new Student[30];
// 随机生成30个学生的姓名和学号
for (int i = 0; i < students.length; i++) {
String name = "学生" + (i + 1);
int id = 10000 + i;
students[i] = new Student(name, id);
}
// 计算全班平均分
double sum = 0;
for (Student student : students) {
sum += student.getAverageScore();
}
double average = sum / students.length;
System.out.println("全班平均分:" + average);
// 随机输出一个同学的成绩
Random random = new Random();
Student randomStudent = students[random.nextInt(students.length)];
System.out.println(randomStudent.getName() + "的成绩:");
int[] scores = randomStudent.getScores();
for (int i = 0; i < scores.length; i++) {
System.out.println("第" + (i + 1) + "门课程:" + scores[i]);
}
}
}
阅读全文