signed

QiShunwang

“诚信为本、客户至上”

Java-集合练习题(1)

2021/6/3 17:14:26   来源:

在这里插入图片描述
测试类:

package coll;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;

public class CollTest {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		//创建集合-》使用泛型,表示只存储Student类的数据
		Collection rgzn = new ArrayList();
		System.out.println("是否添加学生?(1(是) or 2(否))");
		while (sc.nextInt() == 1) {
			//创建对象
			System.out.println("请输入名字:");
			String name = sc.next();
			System.out.println("请输入年龄:");
			int age = sc.nextInt();
			Student s1 = new Student(name,age);
			//添加到集合
			rgzn.add(s1);
			System.out.println("是否继续添加学生?(1(是) or 2(否))");
			if (sc.nextInt() == 1) {
				System.out.println("是否继续添加学生?(1(是) or 2(否))");
				continue;
			}else{
				break;
			}
		}
		//创建迭代器进行遍历
		Iterator<Student> it = rgzn.iterator();
		while (it.hasNext()) {
			Student s = it.next();
		System.out.println("姓名为:"+s.name);
		System.out.println("年龄为:"+s.age);
		}
	}
}

学生类:

package coll;

public class Student {
	String name;
	int age;
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	

}