[내일배움캠프 사전캠프] 달리기반 Day5 퀘스트

맹돌이·2026년 8월 28일

사전캠프

목록 보기
8/11
  1. 단어 맞추기 게임
  2. 컴퓨터가 랜덤으로 영어단어를 선택합니다.
    a.
    영어단어의 자리수를 알려줍니다.
    ex ) PICTURE = 7자리 ⇒ _ _ _ _ _ _ _
    힌트
  3. 사용자는 A 부터 Z 까지의 알파벳 중에서 하나를 입력합니다.
    a.
    입력값이 A-Z 사이의 알파벳이 아니라면 다시 입력을 받습니다
    힌트
    b.
    입력값이 한 글자가 아니라면 다시 입력을 받습니다
    c.
    이미 입력했던 알파벳이라면 다시 입력을 받습니다.
    d.
    입력값이 정답에 포함된 알파벳일 경우 해당 알파벳이 들어간 자리를 전부 보여주고, 다시 입력을 받습니다.
    i.
    ex ) 정답이 eyes 인 경우에 E 를 입력했을 때
  4. _ _ _ → E E _
    e.
    입력값이 정답에 포함되지 않은 알파벳일 경우 기회가 하나 차감되고, 다시 입력을 받습니다.
  5. 사용자가 9번 틀리면 게임오버됩니다.
  6. 게임오버 되기 전에 영어단어의 모든 자리를 알아내면 플레이어의 승리입니다.
package Java_preCourse.Day5;

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

public class Main {
    public static void main(String[] args) {
        //랜덤으로 나올 단어 목록
        String[] words = {"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 random = new Random();
        Scanner sc = new Scanner(System.in);
        //사용자에게 주어진 기회는 9번
        int trials = 9;

        //단어 목록에서 랜덤하게 하나를 뽑아서 randomWord를 선언
        String randomWord =words[random.nextInt(words.length)];

        //사용자에게 맞춰야할 단어를 '_'를 통해서 보여준다
        //사용자가 유효 알파벳을 맞췄을 때, 해당 칸을 알파벳으로 채워야하니까 배열로 선언
        System.out.print("맞춰야할 단어:");
        String[] answer = new String[randomWord.length()];
        for(int i=0; i<randomWord.length(); i++){
            answer[i] = "_";
            System.out.print(answer[i]);
        }
        System.out.println("\n");

        //알파벳이 중복으로 들어가면 안되니까 boolean타입의 배열 생성(알파벳 수만큼)
        boolean[] check = new boolean[26];
        for(int i=0;i<26;i++){
            check[i] = false;
        }

        //정답 입력부
        while(trials>0){
            System.out.println("남은 기회는 "+trials+"번 입니다");
            System.out.print("알파벳(a-z)을 입력하세요:");
            String reply = sc.next();
            sc.nextLine();
            //스캐너는 char를 입력받을 수 없어서, charAt을 이용해 char로 변형
            char alphabet = reply.charAt(0);

            //1.알파벳 하나가 아닌 경우,
            //2.입력했던 알파벳 다시입력하는 경우,
            //3.알파벳이 아닌 경우
            if(reply.length()>1){
                System.out.println("알파벳 하나만 입력해주세요");
                continue;
            }
            if(alphabet<'a'||alphabet>'z'){
                System.out.println("a-z 사이 값만 입력해주세요");
                continue;
            }
            //'a'의 아스키코드는 97이니까 해당 알파벳의 사용성을 체크한다
            if(check[alphabet-97]){
                System.out.println("이미 입력한 값입니다");
                continue;
            }
            
            //정답을 제대로 입력한 경우
            if(randomWord.contains(reply)){
                //정답이 입력된 경우에 answer의 빈칸을 알파벳으로 변경
                for(int j=0; j<randomWord.length(); j++){
                    if(randomWord.charAt(j) == alphabet){
                        answer[j]=reply;
                    }
                    System.out.print(answer[j]);
                }
                trials--;
                //사용된 알파벳을 true로 변경
                check[alphabet-97] = true;
            }
            //오답을 입력한 경우
            else{
                System.out.println("정답에 포함된 알파벳이 아닙니다. 기회가 1 차감됩니다");
                //사용한 알파벳을 true로 변경
                check[alphabet-97]=true;
                trials--;
            }
            
            //승리 조건을 위한 win
            boolean win = true;
            //answer를 돌면서 '_'가 포함되어있는지 체크한다.
            //'_'가 하나라도 있다면 승리가 아니니까 계속,
            for(int i=0;i<answer.length;i++){
                if(answer[i].equals("_")){
                    win = false;
                }
            }
            //승리시 게임 종료
            if (win){
                System.out.println("\n");
                System.out.println("Player Win");
                break;
            }
            System.out.println("\n");
        }
        if(trials>0){
            System.out.println("프로그램을 종료합니다");
        }
        else{
            System.out.println("Player Lose");
            System.out.println("프로그램을 종료합니다");
        }
    }
}

개선하면 좋을 점

  • alphabet-97 을 사용하기 보다는 -‘a'를 사용하는 편이 낫다
  • check 배열은 굳이 false로 초기화하지 않더라도 다 flase로 들어가있다
  • 다음부터는 메서드를 따로 만들어서 사용해보자

0개의 댓글