728x90
반응형
Student.class
package Ex01;
public class Student {
int id;
String tel;
public Student(int id, String tel) {
this.id = id; this.tel = tel;
}
public int getId() {
return this.id;
}
public String getTel() {
return this.tel;
}
}
HashMapStudentEx.class
package Ex01;
import java.util.HashMap;
import java.util.Scanner;
public class HashMapStudentEx {
public static void main(String[] args) {
// 학생 이름과 Student 객체를 쌍으로 저장하는 HashMap 컬렉션 생성
HashMap<String, Student> map = new HashMap<String, Student>();
// 3 명의 학생 저장
map.put("황기태", new Student(1, "010-111-1111"));
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();
}
}
728x90
반응형
'JAVA > 예제' 카테고리의 다른 글
[JAVA] HashMap를 활용한 학생관리 (0) | 2022.10.27 |
---|---|
[JAVA] HashMap을 이용한 입력 및 검색 (0) | 2022.10.27 |
[JAVA] Thread를 활용한 버블게임 (0) | 2022.10.26 |
[JAVA] Vector를 활용한 Polygon 그리기 (0) | 2022.10.26 |
[JAVA] ArrayList를 활용한 학생관리 (0) | 2022.10.26 |
댓글