내일배움캠프(Spring 7기)/내일배움캠프

[사전캠프 퀘스트] 달리기반 - Java 문제풀이

가지코딩 2025. 3. 27. 14:47

📑 목차

  1. Lv1. 랜덤 닉네임 생성기
  2. Lv2. 스파르타 자판기
  3. Lv3. 단어 맞추기 게임
  4. 보너스 문제: 가위 바위 보

* 실습 툴

https://www.mycompiler.io/ko/new/java

 

새 Java 프로그램 만들기 - 마이컴파일러 - myCompiler

실행 코드 코드 저장 기존 코드를 유지하시겠습니까? 에디터에 코드가 있는 동안 언어를 전환하려고 합니다. 이를 유지하려면 “기존 코드 유지”를 선택합니다. 예제로 바꾸려면 “예제로 바

www.mycompiler.io

 

https://www.onlinegdb.com/online_java_compiler

 

Online Java Compiler - online editor

OnlineGDB is online IDE with java compiler. Quick and easy way to run java program online.

www.onlinegdb.com

 


Lv1. 랜덤 닉네임 생성기

랜덤한 닉네임을 생성하는 자바 코드를 작성해보세요.

 

사용자는 최소 27가지 이상의 닉네임 중 하나를 랜덤으로 출력 할 수 있습니다. (아래의 키워드를 사용해주세요!)

  • 기철초풍, 멋있는, 재미있는
  • 도전적인, 노란색의, 바보같은
  • 돌고래, 개발자, 오랑우탄 
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Random;

// The main method must be in a class named "Main".
class Main {
    public static void main(String[] args) {
        String[][] list = {
            {"기철초풍", "멋있는", "재미있는"},
            {"도전적인", "노란색의", "바보같은"},
            {"돌고래", "개발자", "오랑우탄"}
        };

        Random random = new Random();

        for(int i=0; i<3; i++){
            System.out.printf("%s ", list[i][random.nextInt(3)]);
        }
    }
}

 


Lv2. 스파르타 자판기

1. 사용자가 볼 수 있게 메뉴를 표시합니다.

  • 다음과 같은 음료를 실행창에 표시합니다.
    • 사이다 1,700원
    • 콜라 1,900원
    • 식혜 2,500원
    • 솔의눈 3,000원

2. 사용자는 음료를 선택할 수 있습니다. 

  • 사용자에게 어떤 음료를 살 것인지를 입력받습니다.
    • ex) 사이다
    • 목록에 없는 음료일 경우 실행이 종료됩니다.

3.사용자는 지불할 금액을 입력할 수 있습니다.

  • 사용자에게 얼마를 넣을지 입력받습니다.
    • ex) 2000
    • 지불하는 금액이 선택한 음료의 비용보다 작다면 “돈이 부족합니다.” 를 출력합니다
import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    public static void main(String[] args) {
        Map<String, Integer> beverages = Map.of(
            "사이다", 1700,
            "콜라", 1900,
            "식혜", 2500,
            "솔의눈", 3000
        );

        System.out.println("[메뉴]");
        for(String key : beverages.keySet()){
            System.out.printf("%s: %d\n", key, beverages.get(key));
        }
        System.out.println("");

        Scanner in = new Scanner(System.in);
        
        String choice = in.nextLine();
        if (!beverages.containsKey(choice)) {
            System.out.println("목록에 없는 음료입니다.");
            System.exit(0);
        } else {
            System.out.println(choice +"가 선택되었습니다.");
        }

        int coin = in.nextInt();
        if(coin < beverages.get(choice)) {
            System.out.println("돈이 부족합니다.");
        } else {
            System.out.printf("잔액: %d원", coin-beverages.get(choice));
        }
    }
}

Lv3. 단어 맞추기 게임

단어를 주어진 기회 안에 맞추는 게임을 만들어보세요

 

1. 컴퓨터가 랜덤으로 영어단어를 선택합니다.

  • 영어단어의 자리수를 알려줍니다.
    • ex ) PICTURE = 7자리 ⇒ _ _ _ _ _ _ _

2. 사용자는 A 부터 Z 까지의 알파벳 중에서 하나를 입력합니다.

  • 입력값이 A-Z 사이의 알파벳이 아니라면 다시 입력을 받습니다
  • 입력값이 한 글자가 아니라면 다시 입력을 받습니다
  • 이미 입력했던 알파벳이라면 다시 입력을 받습니다.
  • 입력값이 정답에 포함된 알파벳일 경우 해당 알파벳이 들어간 자리를 전부 보여주고, 다시 입력을 받습니다.
    • ex ) 정답이 eyes 인 경우에 E 를 입력했을 때     _ _ _ _ → E _ E _
  • 입력값이 정답에 포함되지 않은 알파벳일 경우 기회가 하나 차감되고, 다시 입력을 받습니다.

3. 사용자가 9번 틀리면 게임오버됩니다.

4. 게임오버 되기 전에 영어단어의 모든 자리를 알아내면 플레이어의 승리입니다.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Random;

// The main method must be in a class named "Main".
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 in = new Scanner(System.in);

        String q = words[random.nextInt(words.length)];
        char[] a = new char[q.length()];
        Arrays.fill(a, '_');
        
        Set<Character> inputChar = new HashSet<>(); 
        
        char input;
        int i=9;
        while(i>0) {
            System.out.println(Arrays.toString(a));
            System.out.printf("현재 남은 기회: %d\n", i);
            System.out.print("A-Z 중 하나를 입력해주세요 ");
            
            input = in.next().toLowerCase().charAt(0);
            System.out.println("");
            
            if (!Character.isLetter(input)) continue;
            if (inputChar.contains(input)) continue;
            inputChar.add(input);
            
            boolean found = false;
            for (int j = 0; j < q.length(); j++) {
                if (q.charAt(j) == input) {
                    a[j] = input;
                    found = true;
                }
            }
            
            if(!found){
                i--;
            }
            
            if (new String(a).equals(q)) {
                System.out.println("\n정답입니다!\n정답은: " + q);
                break;
            }
        }
        
        if (i == 0) {
            System.out.println("\n게임 오버\n정답은: " + q);
        }

    }
}


보너스 문제: 가위 바위 보

5번의 가위바위보 게임을 해서 승리한 횟수 상당의 상품을 받아가는 게임을 만들어봐요

 

1. 5번의 가위바위보를 진행합니다.

 

2. 유저는 매 판마다 “가위”, “바위”, “보” 중 하나를 입력합니다.

  • 잘못된 입력을 받았다면 잘못된 입력입니다! 를 출력해주세요.

3. 컴퓨터는 가위 , 바위, 보 중 랜덤하게 하나를 낼 수 있습니다.

 

4. 매판마다 진행한 가위 바위 보의 승패에 대한 결과를 출력됩니다.

 

5. 5판을 모두 마치면 승리한 횟수에 걸맞는 경품을 획득할 수 있습니다.

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    public static void main(String[] args) {
        String[] option = {"가위", "바위", "보"};
        String[] gift = {"꽝", "곰돌이 인형", "스파르타 랜드 입장권", "스파르타 캐니언 항공 투어권", "호텔 스파르타 숙박권", "스파르테이트 항공권"};
        
        Random random = new Random();
        Scanner in = new Scanner(System.in);
        
        System.out.println("가위, 바위, 보 게임 시작\n");
        
        String input, com;
        int r, inputIndex, result, win=0;
        for(int i=5; i>0; i--){
            System.out.printf("가위, 바위, 보 중 하나를 선택하세요! (남은 횟수: %d) ", i);
            input = in.nextLine();
            r = random.nextInt(3);
            com = option[r];
           
            inputIndex = Arrays.asList(option).indexOf(input);
           
            if(inputIndex < 0) {
               System.out.println("잘못된 입력입니다!\n");
               i++;
               continue;
            }
           
            result = (inputIndex - r + 3) % 3;  // 가위, 바위, 보 승패 패턴
            
            System.out.printf("당신은 %s, 컴퓨터는 %s\n", input, com);
            if (result == 0) {
               System.out.println("비겼습니다. 한번 더!\n");
               i++;
               continue;
            } else if (result == 1) {
                System.out.println("당신의 승리!\n");
                win++;
            } else {
                System.out.println("컴퓨터의 승리!\n");
            }
        }
        
        System.out.printf("총 %d회 승리하여, 경품은 %s!!!\n", win, gift[win]);

    }
}