输入学生信息,然后保存到集合中
学生类:
package Practice;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.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) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
测试类:
package Practice;
import java.util.ArrayList;
import java.util.Scanner;
public class StudentTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList list = new ArrayList();
System.out.println("请录入学生信息");
while (true){
System.out.println("1:继续录入,0:结束录入");
int a = scan.nextInt();
if(a==0){
break;
}
System.out.print("请输入学生姓名:");
String name = scan.next();
System.out.print("请输入学生年龄:");
int aeg = scan.nextInt();
Student s = new Student(name,aeg);
list.add(s);
}
//遍历集合中的学生信息
System.out.println("遍历学生信息:");
for (Object s : list){
System.out.println(s);
}
scan.close();
}
}
结果:
请录入学生信息
1:继续录入,0:结束录入
1
请输入学生姓名:李华
请输入学生年龄:18
1:继续录入,0:结束录入
1
请输入学生姓名:Bob
请输入学生年龄:20
1:继续录入,0:结束录入
0
遍历学生信息:
Student{name='李华', age=18}
Student{name='Bob', age=20}