这个怎么样?
- import java.util.*;
- class TestDemo2
- {
- public static void main(String[] args)
- {
- List<Person> array=new ArrayList<Person>();
- Scanner sc=new Scanner(System.in);
- do
- {
- System.out.println("请录入学生的姓名,输入over结束录入");
- String name=sc.next();
- if(name.toLowerCase().equals("over"))//转成小写并通过equals判断内容是否相等
- break;
- else
- {
- System.out.println("请录入学生的年龄");
- int age=sc.nextInt();
- Person p=new Person(name,age);
- array.add(p);
- }
- }
- while (true);
- Iterator<Person> it=array.iterator();//创建迭代器对象并遍历集合
- while(it.hasNext())
- System.out.println(it.next());
- }
- }
- class Person
- {
- private String name;
- private int age;
- public Person(){}
- public Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
-
- public String getName()
- {
- return name;
- }
- public void setName()
- {
- this.name=name;
- }
- public void setAge()
- {
- this.age=age;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return "Person[name="+name+",age="+age+"]";
- }
- }
复制代码 |