import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Scanner;
class Phone{
private String name, tel;
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
public String getName() {return name;}
public String getTel() {return tel;}
}
public class ex10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String,Phone> hm = new HashMap<String,Phone>();
File f = new File("c:\\temp\\phone.txt");
try {
//입력
int cnt = 0;
Scanner sc1 = new Scanner(new FileReader(f));
while(sc1.hasNext()) {
String str = sc1.nextLine();
String strSplit[] = str.split(" ");
String name = strSplit[0];
String tel = strSplit[1];
hm.put(name, new Phone(name,tel));
cnt++;
}
System.out.println("총 "+ cnt + "개의 전화번호를 읽었습니다.");
//검색 기능
while(true) {
Scanner sc2 = new Scanner(System.in);
System.out.print("이름>> ");
String search = sc2.next();
if(search.equals("그만")) break;
Phone p = hm.get(search);
if(p == null) System.out.println(search + "는 없습니다.");
else System.out.println(p.getTel());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
결과
총 7개의 전화번호를 읽었습니다.
이름>> 최박사
010-2222-3333
이름>> 백점만
011-1100-1100
이름>> 이상아
이상아는 없습니다.
이름>> 이상형
010-3333-4444
이름>> 그만
'명품JAVA프로그래밍 > 8장 입출력 스트림과 파일 입출력' 카테고리의 다른 글
[명품JAVA프로그래밍] 8장 실습문제 9번 (0) | 2022.02.25 |
---|---|
[명품JAVA프로그래밍] 8장 실습문제 8번 (0) | 2022.02.24 |
[명품JAVA프로그래밍] 8장 실습문제 6번 (0) | 2022.02.24 |
[명품JAVA프로그래밍] 8장 실습문제 5번 (0) | 2022.02.24 |
[명품JAVA프로그래밍] 8장 실습문제 4번 (0) | 2022.02.24 |