建立一个对象数组,内放5个学生的数据(学号、姓名、课程名称、成绩),一个学生对象只包含一门课程成绩,定义一个对象指针,指向学生数组,通过该指针调用函数输出最高分的学号、姓名、课程名称、成绩
时间: 2024-10-09 09:08:04 浏览: 63
创建一个学生对象数组并填充数据可以按照以下步骤进行:
首先,我们定义一个名为`Student`的简单类,包含学号、姓名、课程名和成绩属性:
```java
public class Student {
private int studentID;
private String name;
private String courseName;
private double score;
// 构造函数
public Student(int id, String name, String course, double grade) {
this.studentID = id;
this.name = name;
this.courseName = course;
this.score = grade;
}
// 获取和设置分数的方法
public double getScore() { return score; }
public void setScore(double score) { this.score = score; }
@Override
public String toString() {
return "学号:" + studentID + ", 姓名:" + name + ", 课程:" + courseName + ", 成绩:" + score;
}
}
```
然后,我们可以创建一个包含5个学生信息的对象数组,并初始化它们:
```java
public static void main(String[] args) {
Student[] students = new Student[5];
students[0] = new Student(1, "张三", "数学", 95);
students[1] = new Student(2, "李四", "英语", 88);
students[2] = new Student(3, "王五", "物理", 90);
students[3] = new Student(4, "赵六", "化学", 85);
students[4] = new Student(5, "孙七", "生物", 92);
// 创建一个指向学生数组的指针
Student[] ptr = students;
}
```
现在,为了找到最高分的学生信息,我们可以定义一个辅助函数,接受学生数组作为参数:
```java
public static void printHighestScore(Student[] students) {
double maxScore = Double.MIN_VALUE;
Student highestScorer = null;
for (Student student : students) {
if (student.getScore() > maxScore) {
maxScore = student.getScore();
highestScorer = student;
}
}
System.out.println("最高分学生信息:");
System.out.println(highestScorer.toString());
}
// 调用函数输出最高分信息
printHighestScore(ptr);
```
当你运行这个程序,它会输出最高分的学生信息。
阅读全文