创建一个对象数组,数组的元素是学生对象,学生的信息包括学号姓名和成绩
时间: 2023-04-07 10:02:40 浏览: 187
好的,这个问题是可以回答的。您可以这样创建一个对象数组:
```java
class Student {
private String id;
private String name;
private int score;
public Student(String id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
// getter and setter methods
}
// create an array of Student objects
Student[] students = new Student[3];
students[0] = new Student("001", "Alice", 90);
students[1] = new Student("002", "Bob", 80);
students[2] = new Student("003", "Charlie", 70);
```
这样就创建了一个包含三个学生对象的数组,每个学生对象包含学号、姓名和成绩三个属性。
相关问题
创建一个对象数组,数组的元素是学生对象,学生的信息包括学号,姓名和成绩
以下是一个示例代码,创建一个包含三个学生对象的数组:
```java
class Student {
private int id;
private String name;
private double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getGrade() {
return grade;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student(1, "Tom", 89.5);
students[1] = new Student(2, "Jerry", 78.0);
students[2] = new Student(3, "Alice", 92.5);
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + students[i].getId() + ": " + students[i].getName() + " - Grade: " + students[i].getGrade());
}
}
}
```
输出结果:
```
Student 1: Tom - Grade: 89.5
Student 2: Jerry - Grade: 78.0
Student 3: Alice - Grade: 92.5
```
创建一个对象数组,数组的元素是学生对象,学生信息包括学号姓名和成绩,求总人数和平均分
以下是一个示例代码,其中包含一个 `Student` 类来表示学生对象:
```java
public class Student {
private String id;
private String name;
private double score;
public Student(String id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
```
然后,我们可以创建一个 `Student[]` 数组来存储学生对象,然后迭代数组并计算总人数和平均分:
```java
public static void main(String[] args) {
Student[] students = {
new Student("001", "张三", 80),
new Student("002", "李四", 90),
new Student("003", "王五", 70),
new Student("004", "赵六", 85)
};
int total = students.length;
double sum = 0;
for (Student student : students) {
sum += student.getScore();
}
double average = sum / total;
System.out.println("总人数:" + total);
System.out.println("平均分:" + average);
}
```
输出结果:
```
总人数:4
平均分:81.25
```
阅读全文