继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Map的学习笔记

七月_Miss
关注TA
已关注
手记 3
粉丝 5
获赞 0

学生类

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();

	}

}

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP