手记

Map的学习笔记

学生类

import java.util.HashSet;
import java.util.Set;

public class Student {
	public String id;
	public String name;
	public Set<Course> courses;

	public Student(String id, String name) {
		this.id = id;
		this.name = name;
		this.courses = new HashSet<Course>();
	}
}

Map测试类

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class MapTest {
	public Map<String, Student> students;

	public MapTest() {
		students = new HashMap<String, Student>();
	}

	public void getStu() {
		Set<String> st = students.keySet();
		System.out.println("添加的学生如下:");
		for (String string : st) {
			System.out.println(students.get(string).name);

		}
	}

	public void addStu() {
		Scanner sc = new Scanner(System.in);
		int i = 0;
		while (i < 3) {
			System.out.println("please input student id:");
			String id = sc.next();
			if (students.get(id) != null) {
				System.out.println("student exist");
				continue;
			}
			System.out.println("please input student name:");
			String name = sc.next();
			Student s = new Student(id, name);
			students.put(id, s);
			i++;
		}
	}

	public void removeStu() {
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("请输入要删除的学生id:");
			String id = sc.next();
			Student t = students.get(id);
			if (t == null) {
				System.out.println("学生不存在");
				continue;
			}
			students.remove(id);
			break;
		}

	}

	public void disStuEntry() {
		System.out.println("目前学生有:");
		Set<Entry<String, Student>> s = students.entrySet();
		for (Entry<String, Student> entry : s) {
			System.out.println(entry.getKey() + " " + entry.getValue().name);

		}
	}

	public void modifyStu() {
		System.out.println("请输入要修改的学生id:");
		Scanner sc = new Scanner(System.in);
		while (true) {
			String id = sc.next();
			Student stu = students.get(id);
			if (stu == null) {
				System.out.println("该学生不存在,请重新输入。");
				continue;
			}
			System.out.println("当前学生名是: " + stu.name);
			System.out.println("请输入新的名字:");
			String nName = sc.next();
			Student nStu = new Student(id, nName);
			students.put(id, nStu);
			break;
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MapTest t = new MapTest();
		t.addStu();
		t.getStu();
//		t.removeStu();
//		t.disStuEntry();
		t.modifyStu();
		t.disStuEntry();

	}

}

0人推荐
随时随地看视频
慕课网APP