import java.util.Map;
import java.util.Scanner;
public class map {
public static void main(String[] args) {
// 불변 Map 생성
Map<String, Integer> beverages = Map.of(
"사이다", 1700,
"콜라", 1900,
"식혜", 2500,
"솔의눈", 3000
);
System.out.println(beverages);// 맵 내용 출력
System.out.println("구입하고 싶은 음료수를 입력하세요:");
Scanner scanner = new Scanner(System.in);
String userChoice = scanner.nextLine();
for (Map.Entry<String, Integer> beverage : beverages.entrySet()) {
if (beverages.containsKey(userChoice)) {
System.out.println(userChoice);
System.out.println("지불할 금액을 입력하세요:");
int coin = scanner.nextInt();
System.out.println(beverages.get(userChoice));
if (coin < beverages.get(userChoice)) {
// 실행 종료하기
System.out.println("돈이 부족합니다");
} else {
int remain = coin - beverages.get(userChoice);
System.out.println("잔액:"+remain);
}
System.exit(0);
}
}
System.out.println("판매하지 않는 음료수입니다.");
}
}
map은 배열과 다르게 key와 value 값으로 이루어진 자료형이었는데, 배열로 코드 작성한 것보다 더 간단하게 작성할 수 있어 편했다.
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class word {
static int getCharCount(String s) {
int result = 0;
for (int i = 0; i < s.length(); i++) {
result++;
}
return result;
}
public static void main(String[] args) {
System.out.println("영단어 맞추기 게임을 시작하겠습니다!");
String[] quiz = {
"airplane",
"apple",
"arm",
"bakery",
"banana",
"bank",
"bean",
"belt",
"bicycle",
"biography",
"blackboard",
"boat",
"bowl",
"broccoli",
"bus",
"car",
"carrot",
"chair",
"cherry",
"cinema",
"class",
"classroom",
"cloud",
"coat",
"cucumber",
"desk",
"dictionary",
"dress",
"ear",
"eye",
"fog",
"foot",
"fork",
"fruits",
"hail",
"hand",
"head",
"helicopter",
"hospital",
"ice",
"jacket",
"kettle",
"knife",
"leg",
"lettuce",
"library",
"magazine",
"mango",
"melon",
"motorcycle",
"mouth",
"newspaper",
"nose",
"notebook",
"novel",
"onion",
"orange",
"peach",
"pharmacy",
"pineapple",
"plate",
"pot",
"potato",
"rain",
"shirt",
"shoe",
"shop",
"sink",
"skateboard",
"ski",
"skirt",
"sky",
"snow",
"sock",
"spinach",
"spoon",
"stationary",
"stomach",
"strawberry",
"student",
"sun",
"supermarket",
"sweater",
"teacher",
"thunderstorm",
"tomato",
"trousers",
"truck",
"vegetables",
"vehicles",
"watermelon",
"wind"};
Random r1 = new Random();
int index = r1.nextInt(quiz.length);//단어 배열 수 중 답으로 정할 단어 하나를 랜덤으로 고름.
// System.out.println(quiz[index]);//답. 플레이어는 이 답을 볼 수 없다.
char[] question = quiz[index].toCharArray();//답을 char형으로 변형해서 한글자씩 저장
int result = getCharCount(quiz[index]);//랜덤으로 정한 답의 자리수를 구하고
System.out.println("자리수:" + result);//화면에 출력. 플레이어는 이 자리수로 답 유추
/* for(int i=0;i<quiz.length;i++){
System.out.println(quiz[i]);
}
for(String quiz1:quiz){
System.out.println(quiz1);
}*/
Scanner sc = new Scanner(System.in);
int gameover = 9;//게임오버용 9번 틀리면 끝
char[] answer = new char[result];//플레이어가 맞춘 최종 답 배열
for (int i = 0; i < result; i++) {
answer[i] = '_';
}//자리수만큼 기본 값을 _ 문자열로 지정
char[] playerWord;//문자를 char형으로 변환
String cc;//입력받을 문자
boolean check = false; //빈칸체크용
int a = 0; //채운 칸 수
while (true) {//사용자가 9번 틀릴때까지 계속 입력받는다.
System.out.println("알파벳 한 글자를 입력해주세요:");
cc = sc.nextLine();//사용자에게 문자열을 입력받고
playerWord = cc.toCharArray();//char 배열로 변환
if (playerWord.length != 1 || !Character.isLetter(playerWord[0])) {//그 배열이 알파벳이 아니거나 한글자가 아니라면
System.out.println("다시 입력해 주세요.");//다시 입력요구
} else {//입력값이 알파벳 한글자라면
for (int i = 0; i < question.length; i++) {//각 자릿수 비교
if (question[i] == playerWord[0]) {
answer[i] = playerWord[0];//답배열에 문자 넣기
a++;//채운 칸 수
check = true;//맞음 표시
}
}//한 글자로 답 배열을 한 회전 한 후
}
if (!check) {//만약 답이 틀렸다면
gameover--;//기회 한번 놓침
System.out.println(gameover + "번의 기회가 남았습니다.");
if (gameover == 0) {//9번의 기회를 모두 놓쳤다면
System.out.println("플레이어의 패배!");
break;
}
continue;//반복문 처음으로 돌아가기
}
System.out.println(answer);//사용자에게 결과 보여주기
check = false;//다시 리셋
if (a == question.length) {//칸 수를 꽉 채웠다면
System.out.println("플레이어의 승리!");
break;
}
}
}}
생각나는대로 작성했는데 많이 부족한 것 같다. 매번 깔끔하게 정리할 수 없을까..생각하는데 역시 많이 풀어보는 경험밖에 없는 것 같다.