1、在 main 方法中,可以使用如下语句创建学生类的数组:
Student[] students = new Student[5];
其中 "Student" 是学生类的类名,5 是数组的长度。
2、使用 for 循环给数组赋值:
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
students[i].setName("Student " + (i + 1));
students[i].setAge(20 + i);
}
在这个例子中,我们使用一个 for 循环遍历了整个 students 数组。每次循环迭代中,我们使用 "new Student()" 创建了一个新的 Student 对象,并将其赋值给当前循环迭代的数组元素。
3、遍历数组:
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName() + "," + students[i].getAge());
}
这里我们使用另一个 for 循环遍历了整个 students 数组,并将每个学生的姓名和年龄打印出来
注意:上面的例子假设 Student 类有相应的 setName 和 setAge 方法,并且有 getName 和 getAge 方法。