import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class ex11_2 {
private Scanner sc = new Scanner(System.in);
private HashMap<String,String> h = new HashMap<String,String>();
public ex11_2() {
h.put("그리스","아테네");
h.put("일본","도쿄");
h.put("미국","뉴욕");
h.put("영국","런던");
h.put("독일","베를린");
h.put("캐나다","오타와");
h.put("중국","베이징");
h.put("싱가포르","싱가포르");
h.put("인도","뉴델리");
}
private void finish() {
// TODO Auto-generated method stub
System.out.println("게임을 종료합니다.");
}
private void quiz() {
// TODO Auto-generated method stub
Set<String> keys = h.keySet();
Object [] array = (keys.toArray());
while(true) {
int index = (int)(Math.random()*array.length);
String q = (String)array[index];
String a = h.get(q);
System.out.print(q+"의 수도는?");
String answer = sc.next();
if(answer.equals("그만")) break;
if(answer.equals(a)) {
System.out.println("정답!!");
}
else {
System.out.println("아닙니다!!");
}
}
}
private void insert() {
// TODO Auto-generated method stub
int order = h.size();
System.out.println("현재 "+order+"개 나라와 수도가 입력되어 있습니다.");
order++;
while(true) {
System.out.print("나라와 수도 입력"+order+">>");
String nation = sc.next();
if(nation.equals("그만")) break;
String capital = sc.next();
if(contain(nation)) {
System.out.println(nation+"은 이미 있습니다!");
continue;
}
h.put(nation, capital);
order++;
}
}
private boolean contain(String nation) {
if(h.get(nation) != null) {
return true;
}
return false;
}
private void run() {
// TODO Auto-generated method stub
System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
while(true) {
System.out.print("입력:1, 퀴즈:2, 종료:3>>");
int num = sc.nextInt();
switch(num) {
case 1:
insert();
break;
case 2:
quiz();
break;
case 3:
finish();
return;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ex11_2 e = new ex11_2();
e.run();
}
}
결과
**** 수도 맞추기 게임을 시작합니다. ****
입력:1, 퀴즈:2, 종료:3>>1
현재 9개 나라와 수도가 입력되어 있습니다.
나라와 수도 입력10>>한국 서울
나라와 수도 입력11>>그리스 아테네
그리스은 이미 있습니다!
나라와 수도 입력11>>호주 시드니
나라와 수도 입력12>>이탈리아 로마
나라와 수도 입력13>>그만
입력:1, 퀴즈:2, 종료:3>>2
중국의 수도는?베이징
정답!!
인도의 수도는?뉴델리
정답!!
싱가포르의 수도는?하얼빈
아닙니다!!
중국의 수도는?그만
입력:1, 퀴즈:2, 종료:3>>3
게임을 종료합니다.
'명품JAVA프로그래밍 > 7장 제너릭과 컬렉션' 카테고리의 다른 글
[명품JAVA프로그래밍] 7장 실습문제 11-1번 (0) | 2022.02.18 |
---|---|
[명품JAVA프로그래밍] 7장 실습문제 9번 (0) | 2022.02.18 |
[명품JAVA프로그래밍] 7장 실습문제 8번 (0) | 2022.02.18 |
[명품JAVA프로그래밍] 7장 실습문제 7번 (0) | 2022.02.18 |
[명품JAVA프로그래밍] 7장 실습문제 6번 (0) | 2022.02.17 |