영어 단어장 조건 1. 추가, 삭제 가능하게 하기 2. 문제 풀기 기능 만들기
출력 결과 예시
--------------------------
1. 단어 추가
2. 단어 삭제
3. 문제 풀기
--------------------------
메뉴 선택 : (번호 입력)
17개의 풀이가 있습니다.
class Eng_Txt():
def __init__(self) -> None:
self.txt = {}
def add_text(self):
text = input('추가 하실 단어를 입력하세요! : ')
min = input(f'{text}의 뜻을 입력하세요! : ')
self.txt[text] = min
print('정상적으로 추가 되었어요!')
def del_text(self):
text = input('삭제 하실 단어를 입력해주세요! : ')
del self.txt[text]
print('정상적으로 삭제 되었어요!')
def txt_test(self):
while 1:
ko_en = input('영어 한국어로 적기와 한국어 영어로 적기중 무엇으로 테스트를 볼 것입니까? : ')
if ko_en in ['한국어', '영어']:
point = {'정답':0, '오답':0}
if ko_en == '한국어':
for i in self.txt:
text = input(f'{i}의 뜻을 입력해주세요! : ')
if text == self.txt[i]:
point['정답'] += 1
continue
else:
point['오답'] += 1
continue
print(f'정답 : {point["정답"]}, 오답 : {point["오답"]}')
elif ko_en == '영어':
for i in self.txt:
text = input(f'{self.txt[i]}를 영어로 입력해주세요! : ')
if text == i:
point['정답'] += 1
continue
else:
point['오답'] += 1
continue
print(f'정답 : {point["정답"]}, 오답 : {point["오답"]}')
print('"한국어", "영어" 중에 입력해주세요!')
continue
import random
menu_list = ['1', '2', '3', '4', '5', '6']
file_name = 'E:\English_word.txt' #파일명 지정
def print_line():
print('-----------------------')
def print_line2():
print('=======================')
def print_menu():
while (1):
print_line2()
print('1. 단어장 출력')
print('2. 문제 풀기') # 영단어 뜻
print('3. 종료') # 종료
print_line()
print('4. 단어 추가') #a
print('5. 단어 삭제') #w
print('6. 단어장 초기화') #초기화
print_line2()
result = input("메뉴선택 : ")
if result in menu_list:
return result
else:
print("잘못된 선택입니다.")
def f_write():
e_word = input("영단어 입력 : ")
e_mean = input("단어 뜻 입력 : ")
f = open(file_name, 'a')
f.write(e_word + '|' + e_mean + '\n')
f.close()
def f_del():
word = input("삭제할 단어입력 : ")
f = open(file_name, 'r')
lines = f.readlines()
f.close()
x = 0 #삭제 구분자
f = open(file_name, 'w')
for line in lines:
if word + '|' not in line.strip('\n'):
f.write(line)
else:
x = 1
if x == 0:
print("단어를 찾을 수 없습니다.")
else:
print("삭제완료")
f.close()
def init():
init_select = input('초기화 하시겠습니까? (Y)')
if init_select != 'y' and init_select != 'Y':
print("취소")
return
f = open(file_name, 'w')
f.write('')
f.close()
print("초기화 완료")
def f_read():
word_dic = {}
f = open(file_name, 'r')
while(1):
line = f.readline().strip()
if not line:
break
n_word = line.split('|')
if n_word[0] != '':
word_dic.setdefault(n_word[0], n_word[1])
f.close()
return word_dic
def exam():
exam_dic = f_read()
exam_list = []
for i in exam_dic.keys():
exam_list.append(i)
ex_len = len(exam_dic)
ex_num = random.randrange(0, ex_len)
ex_word = exam_list[ex_num]
print('문제 : ' + ex_word)
ex_sel = input('정답 : ')
if ex_sel == exam_dic[ex_word]:
print("정답!")
else:
print("오답입니다.")
while(True):
select = print_menu()
if select == '3': #종료
print("종료")
print_line2()
break
elif select == '1': #단어장 출력
word_dic = f_read()
for key, val in word_dic.items():
print(key + ' : ' + val)
elif select == '2': #문제풀기
exam()
elif select == '4': #단어추가
f_write()
elif select == '5': #단어삭제
f_del()
elif select == '6': #초기화
init()
print_line2()
기능 1. 단어장 목록출력(기본 x) 2. 문제풀기 3. 종료 4. 단어 추가 5. 단어 삭제 6. 단어장 초기화
int main (void)
int a ;
{
printf("-----------------------\n");
printf("1.단어추가\n");
printf("2.단어삭제\n");
printf("3.문제풀기\n");
printf("-----------------------\n");
scanf_s("메뉴선택 : %d, &a);
return 0;
}
def show_menu():
print()
print()
print ('-------------')
print ('1. 단어추가')
print ('2. 단어 삭제')
print ('3. 문제풀기')
print ('4. 단어보기')
print ('-------------')
word={}
while (1):
show_menu()
choice=int(input('메뉴 선택 : '))
if choice==1:
en_word=input('추가하려는 영어 단어를 입력해주세요...')
ko_word=input('추가하려는 영어 단어의 뜻을 입력해주세요...')
word[en_word]=ko_word
print ('단어가 추가되었습니다')
elif choice==2:
en_word=input('삭제하려는 영어 단어를 입력해주세요...')
word.pop(en_word)
print ('단어가 삭제되었습니다')
elif choice==3:
for i in word:
q=i+'의 뜻은 무엇인가요?'
ans=input(q)
if ans==word[i]:
print ('딩동댕')
else:
print ('땡')
elif choice==4:
for i in word:
print ('%15s%15s' %(i,word[i]))
else:
print ('잘못 입력하셨습니다')
dic = {'a':'ㄱ','b':'ㄴ','c':'ㄷ'}
import random
def add():
print('키(영단어) 입력하세요.')
k= input()
print('값(한국어) 입력하세요.')
v= input()
print('저장 되었습니다.')
dic[k]=v
def sub():
print('삭제하고 싶은 영단어를 입력하세요.')
k= input()
del dic[k]
print('삭제되었습니다.')
def q():
dk=list(dic.keys())
ck=random.choice(dk)
print(ck+'의 한국어 뜻은?')
ans=input()
print('당신이 입력한 답은 '+ans+', 답은 '+dic[ck])
def menu():
print('사전내용: ',list(zip(dic.keys(),dic.values())))
print("기능: 1. 단어 추가 2. 단어 삭제 3. 문제풀기")
print('실행할 기능의 번호를 입력하세요.')
mc=int(input())
print('입력한 번호는 '+str(mc))
if mc == 1:
print('단어 추가 실행')
add()
if mc == 2:
print('단어 삭제 실행')
sub()
if mc == 3:
print('문제 풀기 실행')
q()
print('끝')
while True:
menu()
def add(words):
key = input("단어 입력: ")
words[key] = input("뜻 입력: ")
def delete(words):
key = input("제거할 단어: ")
if key in words:
del words[key]
else:
print("해당 단어 없음")
def problem(words):
print("\n\n\n문제지\n")
for i in words:
print(f"{i} : ")
print("\n\n\n")
def mode(num, words):
if num == 1:
add(words)
if num == 2:
delete(words)
if num == 3:
problem(words)
if num == 4:
print(words)
words = {}
num = 3
while num != 5:
num = int(input(
"-----------------\n"
"1. 단어 추가\n"
"2. 단어 삭제\n"
"3. 문제 풀기\n"
"4. 단어장 보기\n"
"5. 종료\n"
"-----------------\n"
"번호 입력 : "
))
mode(num, words)
파이썬입니다.
import random
# Create an empty dictionary to store words
words = {}
# Function to add a word
def add_word():
eng = input("Enter the English word: ")
kor = input("Enter the Korean translation: ")
words[eng] = kor
# Function to delete a word
def delete_word():
eng = input("Enter the English word to delete: ")
del words[eng]
# Function to test the words
def test_words():
score = 0
for eng, kor in words.items():
question = random.choice([eng, kor])
if question == eng:
ans = input(f"What is the Korean translation for {eng}? ")
if ans == kor:
print("Correct!")
score += 1
else:
print(f"Incorrect. The correct answer is {kor}.")
else:
ans = input(f"What is the English translation for {kor}? ")
if ans == eng:
print("Correct!")
score += 1
else:
print(f"Incorrect. The correct answer is {eng}.")
print(f"Total score: {score}/{len(words)}")
# Main menu
while True:
print("--------------------------")
print("1. Add a word")
print("2. Delete a word")
print("3. Test words")
print("--------------------------")
choice = int(input("Menu choice: "))
if choice == 1:
add_word()
elif choice == 2:
delete_word()
elif choice == 3:
test_words()
else:
print("Invalid choice. Please try again.")
print('영어 단어장입니다')
dictionary = [['hello','안녕'],['apple','사과'],['banana','바나나']]
while True:
print("--------------------------\n1. 단어 추가\n2. 단어 삭제\n3. 문제 풀기\n4. 종료\n--------------------------")
a = int(input('메뉴 선택 : '))
if a == 1:
b = input('추가할 단어 입력(영어) : ')
b1 = b.replace(' ','')
c = input('단어의 한글 뜻 입력 : ')
c1 = c.replace(' ','')
e = [b1,c1]
dictionary.append(e)
if a == 2:
aa = 0
for i in dictionary:
print(aa+1,'',dictionary[aa][0])
aa += 1
delete = int(input('삭제하고싶은 단어의 번호를 입력하십시오 : '))
print(dictionary[delete-1][0]+' 가 삭제되었습니다.')
del dictionary[delete-1]
if a == 3:
print('문제풀기를 선택하셨습니다. 영어단어에 맞는 한국어를 입력하십시오.')
bb = 0
for ii in dictionary:
solu = ii[0]+' 의 뜻을 적으시오 : '
solution = input(solu)
solution1 = solution.replace(' ','')
if solution1 == ii[1]:
print('맞추셨습니다!')
else:
print('틀리셨습니다. X')
if a == 4:
break
import random
dictionary = {}
quiz = []
while True:
choose = int(input("""
--------------------------
1. 단어 추가
2. 단어 삭제
3. 문제 풀기
--------------------------
메뉴 선택 : """))
if choose == 1:
word = input("단어를 입력하세요. : ")
quiz.append(word)
mean = input("뜻을 입력하세요 : ")
dictionary[word]=mean
elif choose == 2:
delword = input("삭제할 단어를 입력해주세요 : ")
if delword in dictionary:
del dictionary[delword]
print(dictionary)
else:
print("입력하신 단어가 없습니다 다시 입력하여 주세요")
elif choose == 3:
quiznum = random.randrange(len(quiz))
answer = input("{0}의 뜻은 무엇인가요? : ".format(str(quiz[quiznum])))
if answer == dictionary[str(quiz[quiznum])]:
print("정답!")
else:
print("오답")
else:
print("다시 입력해 주세요")
random = 0
correct = 0
number = 0
con = True
word = ['perfect', 'hard', 'practice', 'like', 'favorite', 'dog', 'love', 'cat', 'python']
mean = ['완벽한', '어려운', '연습하다', '좋아하다', '가장 좋아하는', '개/강아지', '사랑', '고양이', '파이썬']
while con:
print('''--------------------------
1. 단어 추가
2. 단어 삭제
3. 문제 풀기
4. 나가기
--------------------------''')
function = int(input('매뉴선택(번호입력): '))
if function == 1:
new_word = str(input('새 단어를 입력하세요: '))
new_mean = str(input('그 의미를 입력하세요: '))
word.append(new_word)
mean.append(new_mean)
elif function == 2:
del_word = str(input('삭제할 단어를 입력하세요: '))
del_mean = str(input('그 의미를 입력하세요: '))
word.remove(del_word)
mean.remove(del_mean)
elif function == 3:
number = 0
for i in word:
number+=1
print('{0}번 문제'.format(number))
answer = str(input('{0}의 영어단어: '.format(mean[number-1])))
if answer == word[number-1]:
correct+=1
print('정답입니다!')
else:
print('틀렸습니다..')
print('정답은 {0}입니다'.format(word[number-1]))
print('{0}개중에서 {1}개 맞췄습니다'.format(len(word), correct))
correct = 0
number = 0
elif function == 4:
con = False
else:
print('잘못 입력하셨습니다')
import os
import random
fileName="Dict.txt"
def inputData(maxNum):
selectedItem = 0
try:
selectedItem = int(input("메뉴선택 : (번호입력)"))
except:
print("잘못 입력하셧습니다")
if selectedItem > maxNum or selectedItem < 0 :
print("숫자를 잘못 입력하셨습니다")
selectedItem=0
return selectedItem
def fileWrite(data):
file= open(fileName,"w",encoding= 'utf-8')
# file.write("{}".format(dict))
file.write(data)
file.close()
def fileOpen() :
strData = ""
try:
with open(fileName,'r',encoding= 'utf-8') as file:
for line in file:
# print(type(line))
strData += line
except FileNotFoundError as fe:
print("파일이 없습니다")
return strData
#파일 삭제
def init():
value=input("초기화하겠습니까")
if (value == "Y"):
print("파일 삭제합니다")
os.remove(fileName)
# 유형
dict ={}
#init()
strData = fileOpen()
if ( strData != None):
print(eval(strData))
dict=eval(strData)
print(f"있는 데이터는 {dict} 입니다")
Items = {1:"단어추가",2:"단어삭제",3:"문제풀이"}
print("==================================")
print("1. 단어추가")
print("2. 단어삭제")
print("3. 문제풀기")
print("==================================")
maxNum =3
selectedItem =0
while selectedItem == 0:
selectedItem= inputData(maxNum)
print(f"{Items[selectedItem]}을 선택하셨습니다")
if selectedItem == 1 :
key = input("단어를 입력해주세요:")
value = input("뜻을 입력해주세요:")
dict[key] = value
elif selectedItem == 2:
keyArray= dict.keys()
print("===============================")
for k in keyArray :
print(f"대상 : {k}")
print("===============================")
delKey = input("삭제 대상을 입력해주세요:")
if ( delKey in dict.keys()) :
del dict[delKey]
else:
print (f"{delKey} 값이 없습니다")
elif selectedItem == 3:
templist=list(dict.keys())
size =len(templist)
currentRange=random.randrange(0,size)
selectedKey= templist[currentRange]
print(" 크기 :" , size , " 랜덤 값: " , currentRange , "선택 키값:", selectedKey )
print("===============================")
print(" 문제 : ",dict[selectedKey], "의 단어는 ?")
userSelect= input("입력:")
# 사용자가 선택한 문자에서 공백 제거후 비교
if userSelect.strip().upper() == selectedKey.upper():
print("잘 맞췄습니다")
else:
print(f"틀렸습니다 값은 {selectedKey} 입니다")
#print(dict)
#list = (list(zip(dict.keys,dict.values)))
#print(list)
if (selectedItem != 3):
fileWrite("{}".format(dict))
import random
def menu():
print('\n\t')
print('--------------------')
print('1. 단어 추가')
print('2. 단어 삭제')
print('3. 문제 풀기')
print('4. 그 만')
print('--------------------')
vNote = {}
p = '1'
while p != '4':
menu()
p = input('메뉴 선택 : ')
if p == '1':
v = input('단어 입력 : ')
vNote[v] = input('뜻 입력: ')
elif p == '2':
v = input('삭제할 단어: ')
vNote.pop(v)
elif p == '3':
v = random.choice(list(vNote.items()))
ans = input('{}의 뜻은: '.format(v[0]))
if ans == v[1]:
print('정 답')
else:
print('{} 뜻은 {}입니다'.format(v[0], v[1]))
print(vNote)
심심해서 풀어봤는데 예상보다 꽤 걸렸네요....
words={}
def num1():
error=0
eng=input('영문 입력: ')
for i in range(0,len(eng)):
if ord('가')<=ord(eng[i])<=ord('힣'):
print('잘못된 입력')
error+=1
break
kor=input('한글 입력: ')
for i in range(0,len(kor)):
if ord('a')<=ord(kor[i])<=ord('z'):
print('잘못된 입력')
error+=1
break
if error<=0:
words[eng]=kor
def num2():
delete=input('삭제할 영단어를 입력하세요: ')
if delete in words:
del(words[delete])
else:
print('해당 영단어가 사전에 없습니다.')
def num3():
score=0
for i in words.keys():
answer=input("<%s>의 답을 적으시오: "%i)
if answer in words[i]:
print("정답")
score+=1
else:
print("오답")
if __name__=="__main__":
while True:
print('-'*30)
print('1. 단어 추가\n2. 단어 삭제\n3. 문제 풀기')
print('-'*30)
select=int(input("메뉴 선택 : "))
if select==1:
num1()
print(words)
elif select==2:
num2()
print(words)
elif select==3:
num3()
else:
print("잘못된 입력")
package CodingTest1;
import java.util.*;
public class myWordbook implements wordbookfunction {
static Map<String,String> wordbook = new HashMap<String,String>();
public myWordbook() {
wordbook.put("student", "학생(기본단어)");
wordbook.put("apple", "사과(기본단어)");
wordbook.put("people", "사람(기본단어)");
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 english = null;
String korean = null;
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("등록할 영어 단어를 입력하시오 (메뉴로 가려면 menu를 입력) > ");
english = sc.nextLine();
if(english.equals("menu") || english.equals("Menu")) {
break;
} else {
if(wordbook.containsKey(english) == true) {
System.out.println("이미 등록된 단어입니다. 수정을 원하시면 삭제후 다시 등록 해주세요.");
} else {
System.out.print("뜻을 입력하시오 >>" );
korean = sc.nextLine();
try {
wordbook.put(english, korean);
} catch(Exception e) {
System.out.println("다시 입력해주세요");
e.printStackTrace();
} finally {
System.out.println("입력되었습니다.");
}
}
}
}
}
@Override
public void searchWord() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("조회하고 싶은 영단어를 입력하시오. (메뉴로 가려면 menu 입력)");
String eng = sc.nextLine();
if(eng.equals("menu")||eng.equals("Menu")) {
break;
} else {
if(wordbook.containsKey(eng)) {
System.out.println(wordbook.get(eng)); // 한국어 뜻 출력
}else {
System.out.println("등록되지 않은 단어입니다.");
}
}
}
sc.close();
}
@Override
public void deleteWord() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("======= 단어 목록 ======");
Set key = wordbook.keySet();
Iterator iterator;
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next(); // next() 메소드를 사용 할 때마다 적절한 타입으로 캐스팅 해줘야함.
String valueVar = (String) wordbook.get(keyValue);
System.out.println("-" + keyValue + " : " + valueVar);
}
System.out.println("=======================");
System.out.println("삭제하고 싶은 단어를 입력하시오(메뉴로 가려면 menu 입력.)");
String del = sc.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("존재하지 않는 단어입니다.");
}
}
}
sc.close();
}
@Override
public void test() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("1.시작하기 2.종료하기");
int a = sc.nextInt();
if(a==1) {
Set key = wordbook.keySet();
int count = 0;
int totalCount = 0;
Iterator iterator;
System.out.println("<==== 뜻에 맞는 영단어를 입력하시오 ====> ");
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next();
String valueVar = (String) wordbook.get(keyValue);
System.out.println(valueVar);
String answer = sc.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만 입력하시오.");
}
}
sc.close();
}
@Override
public void wordList() {
System.out.println("======= 단어 목록 ======");
Set key = wordbook.keySet();
Iterator iterator;
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next(); // next() 메소드를 사용 할 때마다 적절한 타입으로 캐스팅 해줘야함.
String valueVar = (String) wordbook.get(keyValue);
System.out.println("-" + keyValue + " : " + valueVar);
}
System.out.println("=======================");
}
@Override
public void exit() {
System.out.println("단어장을 종료합니다.");
}
}
``````{.java}
package CodingTest1;
public interface wordbookfunction {
public void Menu();
public void addWord();
public void searchWord();
public void deleteWord();
public void test();
public void wordList();
public void exit();
}
package CodingTest1;
import java.util.*;
public class myWordbook implements wordbookfunction {
static Map<String,String> wordbook = new HashMap<String,String>();
public myWordbook() {
wordbook.put("student", "학생(기본단어)");
wordbook.put("apple", "사과(기본단어)");
wordbook.put("people", "사람(기본단어)");
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 english = null;
String korean = null;
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("등록할 영어 단어를 입력하시오 (메뉴로 가려면 menu를 입력) > ");
english = sc.nextLine();
if(english.equals("menu") || english.equals("Menu")) {
break;
} else {
if(wordbook.containsKey(english) == true) {
System.out.println("이미 등록된 단어입니다. 수정을 원하시면 삭제후 다시 등록 해주세요.");
} else {
System.out.print("뜻을 입력하시오 >>" );
korean = sc.nextLine();
try {
wordbook.put(english, korean);
} catch(Exception e) {
System.out.println("다시 입력해주세요");
e.printStackTrace();
} finally {
System.out.println("입력되었습니다.");
}
}
}
}
}
@Override
public void searchWord() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("조회하고 싶은 영단어를 입력하시오. (메뉴로 가려면 menu 입력)");
String eng = sc.nextLine();
if(eng.equals("menu")||eng.equals("Menu")) {
break;
} else {
if(wordbook.containsKey(eng)) {
System.out.println(wordbook.get(eng)); // 한국어 뜻 출력
}else {
System.out.println("등록되지 않은 단어입니다.");
}
}
}
sc.close();
}
@Override
public void deleteWord() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("======= 단어 목록 ======");
Set key = wordbook.keySet();
Iterator iterator;
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next(); // next() 메소드를 사용 할 때마다 적절한 타입으로 캐스팅 해줘야함.
String valueVar = (String) wordbook.get(keyValue);
System.out.println("-" + keyValue + " : " + valueVar);
}
System.out.println("=======================");
System.out.println("삭제하고 싶은 단어를 입력하시오(메뉴로 가려면 menu 입력.)");
String del = sc.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("존재하지 않는 단어입니다.");
}
}
}
sc.close();
}
@Override
public void test() {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("1.시작하기 2.종료하기");
int a = sc.nextInt();
if(a==1) {
Set key = wordbook.keySet();
int count = 0;
int totalCount = 0;
Iterator iterator;
System.out.println("<==== 뜻에 맞는 영단어를 입력하시오 ====> ");
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next();
String valueVar = (String) wordbook.get(keyValue);
System.out.println(valueVar);
String answer = sc.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만 입력하시오.");
}
}
sc.close();
}
@Override
public void wordList() {
System.out.println("======= 단어 목록 ======");
Set key = wordbook.keySet();
Iterator iterator;
for(iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next(); // next() 메소드를 사용 할 때마다 적절한 타입으로 캐스팅 해줘야함.
String valueVar = (String) wordbook.get(keyValue);
System.out.println("-" + keyValue + " : " + valueVar);
}
System.out.println("=======================");
}
@Override
public void exit() {
System.out.println("단어장을 종료합니다.");
}
}
ackage CodingTest1;
import java.util.*;
public class wordbook {
public static void main(String[] args) {
myWordbook mybook = new myWordbook();
Scanner sc = new Scanner(System.in);
while(true) {
mybook.Menu();
int select = sc.nextInt();
switch(select){
case 1:
mybook.addWord();
break;
case 2:
mybook.searchWord();
break;
case 3:
mybook.deleteWord();
break;
case 4:
mybook.test();
break;
case 5:
mybook.wordList();
break;
case 6:
mybook.exit();
break;
}
if(select>6) {
System.out.println("1~6까지의 숫자만 입력하시오 >> ");
}
}
}
}
def add_word(words: dict, input_eng, input_kr):def add_word(words: dict, input_eng, input_kr):
words[input_eng] = input_kr
return words
def del_word(words: list, input_eng):
del words[input_eng]
return words
def search_word(words: list, input_eng, input_kr):
if words[input_eng] == input_kr:
return True
else:
return False
def print_dict(words):
print(words)
def select_menu():
display_string = f"""{'-'*30}
1. 단어 추가
2. 단어 삭제
3. 문제 풀기
4. 단어장 펼쳐보기
{'-'*30}"""
words = {}
while True:
try:
print(display_string)
input_num = int(input("메뉴 선택 : (번호 입력)"))
if input_num not in [1, 2, 3,4 ]:
print("1, 2, 3 이외의 값을 입력하셨습니다.")
continue
elif input_num == 1:
print("단어 추가 옵션을 선택 하셨습니다.")
input_eng = input("영어단어를 입력해주세요. ")
input_kr = input("한글로 뜻을 입력해주세요. ")
words = add_word(words, input_eng, input_kr)
elif input_num == 2:
print("단어 삭제 옵션을 선택 하셨습니다.")
input_eng = input("영어단어를 입력해주세요. ")
words = del_word(words, input_eng)
elif input_num == 3:
if words:
print("문제 풀기 옵션을 선택하셨습니다.")
input_eng = input("영어단어를 입력해주세요. ")
input_kr = input("한글로 뜻을 입력해주세요. ")
if search_word(words, input_eng, input_kr):
print(f"정답입니다. {input_eng} ---> {input_kr}")
else:
print(f"오답입니다. {input_eng} ---> {input_kr}")
else:
print("단어장이 비어있습니다. 단어 추가 후, 해당 메뉴를 선택해주세요.")
elif input_num == 4:
print_dict(words)
else:
pass
except Exception as e:
continue
if __name__ == '__main__':
select_menu()
word = {}
a = None
while True:
print('''1. 단어 추가
2. 단어 삭제
3. 문제 풀기''')
A = input('메뉴를 골라주세요 :')
if A == '1':
A1 = input('추가할 단어를 말해주세요 :')
a = input('뜻을 말해주세요 :')
word[A1]=a
print('단어 목록 :',word)
elif A == '2':
A2 = input('어떤 단어를 삭제할까요? :')
word.pop(A2)
print('단어 목록 :',word)
elif A == '3':
for x in word:
print(x,'의 뜻은 무엇인가요?')
a = input('답 :')
if a == word[x]:
print('정답')
else:
print('땡')
딕셔너리를 이용하여 만들어 봤습니다.