김호진02 2024. 10. 22. 21:48

 

import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String[] word = {"SPARTA", "PICTURE", "SNACK", "QUAKE", "BREEZE",
                "SWIFT", "SHINY", "GLARE", "CRISP", "FLICKER", "JOLLY", "GLINT", "TWIRL"};

        Scanner sc = new Scanner(System.in);
        int cnt = 0; //남은 기회 카운팅

        Random rm = new Random();
        int rm_index = rm.nextInt(word.length);
        // 랜덤 단어를 선택
        String result = word[rm_index];//result에 랜덤단어 저장
       // System.out.println(result); //정답 확인용

        char[] ch_word = new char[10]; // 입력값 임시 저장소


        int tmp = 0;
        while (cnt < 9) {
            System.out.print("입력: ");
            String input = sc.nextLine();

            char ch_input = input.toUpperCase().charAt(0);
            if (input.length() >= 2) { //2글자 이상 입력 시 재입력!
                System.out.println("한글자만 입력하셔야 합니다!");
                continue;
            } else if (already(ch_word, ch_input)) { // 입력한 값(정답) 재 입력시 다시
                cnt++;
                System.out.println("이미 입력한 값 입니다.");
                System.out.println("남은기회 : "+ (9-cnt));
                continue;
            } else if (!Character.isLetter(input.charAt(0))) { // 잘못된 문자일경우(영문자가 아닌경우)
                System.out.println("잘못된 입력값 입니다! a~z로 입력해주세요!");
            } else if (result.contains(input.toUpperCase())) { // 정답인경우
                ch_word[tmp] = ch_input;
                cnt++;
                tmp++;
                System.out.print("정답! ");
                System.out.println("남은기회 : "+ (9-cnt));
            } else { // 오답일 경우
                cnt++;
                System.out.print("오답입니다! ");
                System.out.println("남은기회 : "+ (9-cnt));
                continue;
            }

            String stmp=""; // 정답을 모두 맞췄을경우 사용할 tmp문자열
            for (int i = 0; i < result.length(); i++) {
                if (already(ch_word,result.charAt(i))) {
                    System.out.print(result.charAt(i));
                    stmp+=result.charAt(i);
                } else {
                    System.out.print("_");
                }
            }
            System.out.println();
            if(stmp.equals(result)){
                System.out.println();
                System.out.println("***************");
                System.out.println("정답을 모두 맞췄습니다!");
                System.out.println("남은기회 "+ (9-cnt));
                System.out.println("정답 : "+result);
                System.out.println("***************");
                return;

            }
        }
    }
    public static Boolean already(char[] a, char b) {
        for (char i : a) {
            if (i == b) {
                return true;
            }
        }
        return false;
    }
}

 

Character.isLetter(문자)
: 문자가 a-z인경우 true 아니면 false 반환

다 맞추지 못했을 때