[Java] 단어장 만들기개발자가 되기까지 (2023.08.16~2024.04.15)/[Basic] Java2023. 10. 10. 21:19
Table of Contents
<문제>
단어장 만들기 |
단어 : 의미 기본 단어 - hello : 안녕 - apple : 사과 - banana : 바나나 단어를 추가, 출력(정렬해서 출력), 검색, 삭제 |
<방법>
public class Word<K, V> {
private K word;
private V mean;
public Word() {}
public Word(K word, V mean) {
this.word = word;
this.mean = mean;
}
public K getWord() {
return word;
}
public void setWord(K word) {
this.word = word;
}
public V getMean() {
return mean;
}
public void setMean(V mean) {
this.mean = mean;
}
@Override
public String toString() {
return word + " : " + mean;
}
}
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class WordManager {
ArrayList<Word<String, String>> words = new ArrayList<>();
public WordManager() {
addWord();
}
public void addWord() {
words.add(new Word("hello", "안녕" ));
words.add(new Word("apple", "사과" ));
words.add(new Word("banana", "바나나" ));
}
//메뉴 추가
public void add(Scanner scan) {
System.out.print("단어> ");
String w = scan.next();
System.out.print("의미> ");
String m = scan.next();
words.add(new Word(w,m));
System.out.println("***** 메뉴 추가 완료 *****");
}
// 출력
public void printList() {
System.out.println("---Word List---");
for (int i = 0; i < words.size(); i++) {
System.out.println((i + 1) + ". " + words.get(i));
}
System.out.println("------------------");
}
// TreeSet 오름차순
public void printAsc() {
TreeSet<String> wordList = new TreeSet<>();
int index = 1;
for(int i = 0; i < words.size(); i++) {
wordList.add(words.get(i).getWord()+": "+words.get(i).getMean());
}
for(String str : wordList) {
System.out.println(index + ". " + str);
index++;
}
}
// 검색
public void searchWord(Scanner scan) {
System.out.print("검색단어> ");
String search = scan.next();
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getWord().equals(search)) {
System.out.println(words.get(i));
}
}
}
//삭제
public void deleteWord(Scanner scan) {
System.out.print("삭제단어> ");
String delWord = scan.next();
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getWord().equals(delWord)) {
System.out.println("["+delWord+"] 삭제합니다.");
words.remove(i);
}
}
}
}
import java.util.Scanner;
public class WordMain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
WordManager wm = new WordManager();
//출력
wm.printList();
System.out.println(); // 줄바꿈
System.out.println("--단어추가--");
wm.add(scan);
System.out.println(); // 줄바꿈
wm.printList();
System.out.println(); // 줄바꿈
System.out.println("--단어장 정렬--");
wm.printAsc();
System.out.println(); // 줄바꿈
System.out.println("--검색--");
wm.searchWord(scan);
System.out.println(); // 줄바꿈
System.out.println("--삭제--");
wm.deleteWord(scan);
wm.printList();
System.out.println("--삭제된 단어장 정렬--");
wm.printAsc();
}
}
[Java] 단어장 만들기 끝!
(다음 게시물 예고편)
[Java] Stream을 활용하여 점수 출력
728x90
@rlozlr :: 얼렁뚱땅 개발자
얼렁뚱땅 주니어 개발자
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!