创建一个存储学生对象的集合,存储3个学生对象,遍历集合,学生姓名和年龄来自于键盘录入
public class scanner {
/*
分析:
1.定义一个学生类
2。创建集合对象
3.键盘录入信息,封装信息
4.创建、添加3个学生对象
5.遍历集合,打印结果
*/
public static void main(String[] args) {
ArrayList<Student1> stu = new ArrayList<>();
Student1 a1 = getStudentinformation();
Student1 b1 = getStudentinformation();
Student1 c1 = getStudentinformation();
//添加学生对象
stu.add(a1);
stu.add(b1);
stu.add(c1);
for (int i = 0; i < stu.size(); i++) {
Student1 s = stu.get(i);
System.out.println(s.getName()+s.getAge());
}
}
public static Student1 getStudentinformation(){
//键盘录入信息
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名:");
String name = sc.next();
System.out.println("请输入学生年龄:");
int age = sc.nextInt();
//创建学生对象,把信息赋值给成员变量
Student1 a = new Student1(name,age);
return a;
}
}
//定义一个学生类
class Student1{
private String name;
private int Age;
public Student1() {
}
public Student1(String name, int age) {
this.name = name;
Age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
}
运行结果为: