需求:创建一个存储学生对象的集合,存储5个学生对象,使用程序实现在控制台遍历该集合
package com.collection.Demo02;public class Student {private String userName;private int age;/*** 给成员属性赋值* 1.构造方法* 2.set方法*/public Student(String userName, int age) {this.userName = userName;this.age = age;}@Overridepublic String toString() {return "Student{" +"userName='" + userName + '\'' +", age=" + age +'}';}public String getUserName() {return userName;}public int getAge() {return age;}
}
package com.collection.Demo02;import java.util.ArrayList;public class Test01 {public static void main(String[] args) {//1.创建5个学生对象Student s1 = new Student("name1", 20);Student s2 = new Student("name2", 20);Student s3 = new Student("name3", 20);Student s4 = new Student("name4", 20);Student s5 = new Student("name5", 20);//2.学生集合ArrayList<Student> students = new ArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);students.add(s5);System.out.println("存入5个学生对象成功");System.out.println("开始遍历集合中学生对象");//3.遍历集合中的数据for (Student student : students) {System.out.println("学生姓名:" + student.getUserName() + " 学生年龄:" + student.getAge());
// System.out.println(student.toString());}}
}
运行结果:
优化
∵ 在创建学生对象的时候,把学生的信息写死了
∴ 改为键盘录入
package com.collection.Demo02;import java.util.ArrayList;
import java.util.Scanner;/*** 优化*/
public class Test02 {public static void main(String[] args) {ArrayList<Student> students = new ArrayList<>();for (int i = 1; i <= 5; i++) {Scanner sc = new Scanner(System.in);System.out.print("请输入第" + i + "位学生姓名:");String userName = sc.nextLine();System.out.print("请输入第" + i + "位学生年龄:");int age = sc.nextInt();students.add(new Student(userName, age));System.out.println("======================");}for (Student student : students) {System.out.println("学生姓名:" + student.getUserName() + " 学生年龄:" + student.getAge());}}
}
运行结果:
下一篇文章: