先创建Student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(java.lang.String name, int age) {
this.name = name;
this.age = age;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
再创建测试类
import java.util.ArrayList;
import java.util.Scanner;
public class StudentTest2 {
public static void main(String[] args) {
//创建对象
ArrayList<Student>list=new ArrayList<>();
//键盘录入学生信息并添加到集合中
Scanner sc=new Scanner(System.in);
for(int i=0;i<3;i++){
Student s=new Student();
System.out.println("请输入学生姓名");
String name=sc.next();
System.out.println("请输入学生年龄");
int age=sc.nextInt();
s.setName(name);
s.setAge(age);
list.add(s);
}
//遍历集合
for(int i=0;i<list.size();i++){
Student stu=list.get(i);
System.out.println(stu.getName()+","+stu.getAge());
}
}
}
上面我设置的录入三个学生信息,也可根据实际情况更改。