웹개발/Java & JavaScript

[Java 개념정리] HashMap 을 이용한 영어단어장[코드]

건뱅 2019. 2. 22.
반응형

<< 태클은 환영입니다 >>

  < 잘못됬다던가, 수정했으면 좋겠다 또는 더 좋은방법이 있다면 알려주세요 >


1. wordbookfunction.java (인터페이스)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.java.wordbook;
 
public interface wordbookfunction {
    
    public void Menu();         //메뉴선택화면
    public void addword();        //단어 등록
    public void wordsearch();    //단어 조회
    public void deleteword();    //단어 삭제
    public void test();            //단어 테스트
    public void wordlist();        //등록단어목록보기
    public void exit();            //종료
    
}
 
cs


2. mywordbook.java (wordbookfunction 인터페이스를 상속받음)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package com.java.wordbook;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
 
public class mywordbook implements wordbookfunction {
 
    static HashMap<StringString> wordbook = new HashMap<>(); // 컴파일시 메모리 할당(static), 공유목적
 
    // 생성자
    public mywordbook() {
        wordbook.put("student""학생(기본단어)");
        wordbook.put("people""사람,닝겐(기본단어)");
        wordbook.put("apple""사과(기본단어)");
        wordbook.put("pizza""피자(기본단어)");
    }
 
    // 메뉴
    @Override
    public void Menu() {
 
        System.out.println("등록된 단어수: " + wordbook.size());
        System.out.println("-----하고싶은 것을 선택해주세요-----");
        System.out.println("1.단어등록");
        System.out.println("2.단어조회");
        System.out.println("3.단어삭제");
        System.out.println("4.테스트");
        System.out.println("5.단어목록보기");
        System.out.println("6.종료");
        System.out.println("----------------------------");
    }
 
    // 단어등록
    @Override
    public void addword() {
 
        String eng = null;
        String kor = null;
        while (true) {
 
            Scanner scr = new Scanner(System.in);
            System.out.print("등록할 영어단어를 입력하세요(Menu로 가려면 menu입력):");
            eng = scr.nextLine();
            if (eng.equals("menu"|| eng.equals("Menu")) { // String 변수 비교시 .equals사용
                break;
            } else {
                if (wordbook.containsKey(eng) == true) {// key에대한 값이 존재하면
                    System.out.println("이미 등록된 단어입니다. 수정을 원하시면 삭제후 다시 등록해 주세요.");
                } else { // 등록이안된 단어일경우
                    System.out.print("뜻을 입력하세요: ");
                    kor = scr.nextLine();
 
                    try {
                        wordbook.put(eng, kor);
                    } catch (Exception e) {
                        System.out.println("다시입력해주세요");
                        e.printStackTrace();
                    } finally {
                        System.out.println("입력되었습니다.");
                    }
                }
            }
        }
    }
 
    // 단어조회
    @Override
    public void wordsearch() {
        while (true) {
            Scanner scr = new Scanner(System.in);
            System.out.println("조회하고싶은 영단어를 입력하세요(Menu로가려면 menu입력):");
            String eng = scr.nextLine();
            if (eng.equals("menu"|| eng.equals("Menu")) {
                break;
            } else {
                if (wordbook.containsKey(eng) == true) {// 검색한 영단어가 key값에 존재하면
                    System.out.println(wordbook.get(eng)); // 입력한 key에 대응되는 value 출력
                } else {
                    System.out.println("등록되지 않은 단어입니다.");
                }
            }
        }
    }
 
    // 단어삭제
    @Override
    public void deleteword() {
        while (true) {
            Scanner scr = new Scanner(System.in);
            System.out.println("====단어 목록====");
            Set key = wordbook.keySet();
            Iterator iterator; // map전체 출력시 iterator 사용
 
            for (iterator = key.iterator(); iterator.hasNext();) {
                String keyValue = (String) iterator.next();// key값출력
                String valueVar = (String) wordbook.get(keyValue);// value값출력
 
                System.out.println("*" + keyValue + " : " + valueVar);
 
            }
            System.out.println("=============");
 
            System.out.println("삭제하고 싶은 단어를 입력하세요(Menu로가면 menu입력:");
            String del = scr.nextLine();
            if (del.equals("menu"|| del.equals("Menu")) {
                break;
            } else {
                if (wordbook.containsKey(del) == true) {
                    System.out.println("입력한 단어 (" + del + ":" + wordbook.remove(del) + ")가 삭제되었습니다.");
                } else {
                    System.out.println("존재하지 않는 단어입니다.");
                }
            }
        }
    }
 
    // 단어 테스트
    @Override
    public void test() {
        // TODO Auto-generated method stub
        while (true) {
            Scanner scr = new Scanner(System.in);
            System.out.println("1.시작하기");
            System.out.println("2.종료하기");
            int a = scr.nextInt();
            if (a == 1) {
                Set key = wordbook.keySet();
                int count = 0;
                int totalCount = 0;
                Iterator iterator; // map전체 출력시 iterator 사용
                System.out.println("<====뜻에 맞는 영단어를 입력하세요====>");
                for (iterator = key.iterator(); iterator.hasNext();) {
                    String keyValue = (String) iterator.next();// key값
                    String valueVar = (String) wordbook.get(keyValue);// value값
                    Scanner scan = new Scanner(System.in);
                    System.out.println(valueVar);
                    String answer = scan.nextLine();
 
                    if (answer.equals(keyValue)) {
                        System.out.println("정답입니다.");
                        count++;
                        totalCount++;
                    } else {
                        System.out.println("틀렸습니다.  (답:" + keyValue + ")");
                        totalCount++;
                    }
                }
                System.out.println("<<결과 : " + count + "/" + totalCount + ">>");
                break;
 
            } else if (a == 2) {
                break;
            } else {
                System.out.println("1 또는 2만입력해주세요");
            }
        }
    }
 
    // 등록된 단어목록
    @Override
    public void wordlist() {
        System.out.println("-------------목록---------------");
//     System.out.println(wordbook.toString());
 
        Set key = wordbook.keySet();
 
        Iterator iterator; // map전체 출력시 iterator 사용
 
        for (iterator = key.iterator(); iterator.hasNext();) {
            String keyValue = (String) iterator.next();// key값출력
            String valueVar = (String) wordbook.get(keyValue);// value값출력
 
            System.out.println("*" + keyValue + " : " + valueVar);
 
        }
        System.out.println("-------------------------------");
 
        while (true) {
            System.out.println("돌아가려면 menu입력");
            Scanner scr = new Scanner(System.in);
            String menu = scr.nextLine();
            if (menu.equals("menu")) {
                break;
            } else {
                System.out.println("오류");
            }
        }
    }
 
    // 종료
    @Override
    public void exit() {
        System.out.println("단어장을 종료합니다.");
 
    }
 
}
 
cs


3. wordbook.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.java.wordbook;
 
import java.util.Scanner;
import com.java.wordbook.*;
 
public class wordbook {
 
    public static void main(String[] args) {
 
        mywordbook mybook = new mywordbook(); // 객체생성(클래스 객체)
        while (true) {
 
            // 메인화면(메뉴)
            mybook.Menu();
 
            // 메뉴선택
            Scanner scan = new Scanner(System.in);
            String select = scan.nextLine();
 
            if (select.equals("1")) {
                mybook.addword();
            } else if (select.equals("2")) {
                mybook.wordsearch();
 
            } else if (select.equals("3")) {
                mybook.deleteword();
            } else if (select.equals("4")) {
                mybook.test();
            } else if (select.equals("5")) {
                mybook.wordlist();
            } else if (select.equals("6")) {
                mybook.exit();
                break;
            } else {
                System.out.println("1~6까지의 숫자만 입력하세요.");
            }
        }
    }
}
 
cs


4. 실행화면


길어지는 관계로 이정도만 올립니다.(궁금하신분은 복사붙여넣기하여 실행해보세용)

추후 스프링에서도 구현해볼 생각입니다. 만들게되면 올려보도록할게요ㅎㅎ

반응형

댓글