[자바기초] HashMap으로 [학생 이름, Student 객체]를 이용하여 저장, 출력


package com.ljh.map;

import java.util.HashMap;
import java.util.Scanner;

class Student { 
	private int id;
	private String tel;
	public Student(int id, String tel) { this.id = id; this.tel = tel; }
	public int getId() { return id; }
	public String getTel() { return tel; }	
}

public class HashMapStudentEx {
	public static void main(String[] args) {
		//HashMap으로 [학생 이름, Student 객체]를 이용하여 저장, 출력
		HashMap map = new HashMap();	
		map.put("황기태", new Student(1, "010-111-1111")); // 3명의 학생 저장 
		map.put("이재문", new Student(2, "010-222-2222"));
		map.put("김남윤", new Student(3, "010-333-3333"));
		
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.print("검색할 이름?");
			String name = scanner.nextLine(); // 사용자로부터 이름 입력
			if(name.equals("exit")) 
				break; // while 문을 벗어나 프로그램 종료
			Student student = map.get(name);  // 이름에 해당하는 Student 객체 검색
			if(student == null)
				System.out.println(name + "은 없는 사람입니다.");
			else
				System.out.println("id:" + student.getId() + ", 전화:" + student.getTel());
		}
		scanner.close();
	}
}

댓글

이 블로그의 인기 게시물

[자바기초] jxl을 이용하여 자바에서 엑셀파일 읽고,쓰기

[자바기초] Vector, Iterator를 이용해서 정수 삽입후 모든 정수 출력 및 합산