11-48~51 HashMap(2)

oyeon·2020년 12월 27일
0

Java 개념

목록 보기
36/70

예제 1

public static void main(String[] args){
	HashMap map = new HashMap();
	map.put("myId", "1234");
	map.put("asdf", "1111");
	System.out.println(map);
	map.put("asdf", "1234");
	System.out.println(map);
	
	Scanner s = new Scanner(System.in); // 화면으로부터 라인단위로 입력
	
	while(true) {
		System.out.println("id와 password를 입력해 주세요.");
		System.out.print("id :");
		String id = s.nextLine().trim();
		
		System.out.print("password :");
		String password = s.nextLine().trim();
		System.out.println();
		
		if(!map.containsKey(id)) {
			System.out.println("입력한 id가 없습니다. 다시 입력하세요.");
			continue;
		}
		if(!(map.get(id)).equals(password)) {
			System.out.println("비밀번호가 틀립니다. 다시 입력하세요.");
		} else {
			System.out.println("id와 비밀번호가 일치합니다.");
			break;
		}
	}
}

예제 2

public static void main(String[] args){
	
	HashMap map = new HashMap();
	map.put("김자바", new Integer(90));
	map.put("김자바", new Integer(100));
	map.put("박자바", new Integer(100));
	map.put("최자바", new Integer(80));
	map.put("이자바", new Integer(90));

	Set set = map.entrySet();
	Iterator it = set.iterator();
	
	while(it.hasNext()) {
		// Map 인터페이스, Entry 인터페이스(Map의 내부 인터페이스)
		Map.Entry e = (Map.Entry)it.next();
		System.out.println("이름: "+ e.getKey() +", "
				+"점수: "+ e.getValue());
	}
	
	set = map.keySet();
	System.out.println("참가자 명단: " + set);
	
	Collection values = map.values();
	it = values.iterator();
	
	int total = 0;
	
	while(it.hasNext()) {
		int i = (int)it.next();
		total += i;
	}
	System.out.println("총점 : " + total);
	System.out.println("평균 : " + (float)total/set.size());
	System.out.println("최고점수 : " + Collections.max(values));
	System.out.println("최저점수 : " + Collections.min(values));
}
profile
Enjoy to study

0개의 댓글