java中1、在main方法中,创建学生类的数组;+2、使用for循环给数组赋值。+3?

1、在main方法中,创建学生类的数组;

2、使用for循环给数组赋值。

3、遍历数组

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 方法。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2023-02-13
public class Student { String name; int age; String gender; } public class Main { public static void main(String[] args) { //1、创建学生类的数组 Student[] students = new Student[3]; //2、使用for循环给数组赋值 for (int i = 0; i < students.length; i++) { Student stu = new Student(); stu.name = "学生" + (i + 1); stu.age = 18 + i; stu.gender = i % 2 == 0 ? "男" : "女"; students[i] = stu; } //3、遍历数组,输出每个学生的信息 for (int i = 0; i < students.length; i++) { System.out.println("学生姓名:" + students[i].name); System.out.println("学生年龄:" + students[i].age); System.out.println("学生性别:" + students[i].gender); System.out.println("------------------"); } } }
第2个回答  2023-02-14
public class Test {
public static void main(String[] args) {
// 1、创建学生类的数组
Student[] students = new Student[5];
// 2、使用for循环给数组赋值
for (int i = 0; i < students.length; i++) {
students[i] = new Student("学生" + i, i);
}
// 3、遍历数组,以 Makrdown 格式输出
System.out.println("|姓名 | 年龄 |");
System.out.println("|:----:|:----:|:----:|");
for (Student student : students) {
System.out.println("|" + student.getName() + " | " + student.getAge() + " |");
}
}
}
相似回答
大家正在搜