JAVA 프로그래밍

[JAVA] 풀스택 개발자 부트캠프 008일차 ③ 주사위 숫자 맞히기

selfdailycoding 2025. 1. 7. 11:13

클래스를 완성하시오.
주사위 게임을 하는 Game 클래스이다.
주사위의 숫자를 유저가 맞추는 게임으로
랜덤으로 주사위의 숫자를 취득하고 유저로부터 입력받아 판정한다.


import java.util.Scanner;

public class MainClass {

    public static void main(String[] args) {

        Game game = new Game();

        game.play();

    }
}
class Game{
    int com;
    int user;
    boolean clear;
    int win = 0;
    int lose = 0;

    Scanner sc = new Scanner(System.in);    // -> heap

    // random 주사위는 셋팅
    void init(){    // initialize(초기화)
        clear = false;
        com = (int)(Math.random() * 6) + 1;
    }

    // user input
    void userInput(){
        //Scanner sc = new Scanner(System.in);  // --> stack
        System.out.print("예상 수 = ");
        user = sc.nextInt();
    }

    // 판정
    void finding(){
        if (user == com) {
            clear = true;
            win++;
        }else{
            lose++;
        }
    }

    // 결과출력
    void result(){
        System.out.println("주사위 수:" + com);

        if(clear){
            System.out.println("축하합니다 맞추셨습니다");
        }else{
            System.out.println("아쉽습니다. 다시 도전하세요");
        }

        System.out.println("전적은 " + win + "승 " + lose + "패 입니다");
    }

    void play(){
        //Scanner sc = new Scanner(System.in);
        while(true) {
            init();
            userInput();
            finding();
            result();

            System.out.print("play again? (y/n) = ");
            String msg = sc.next();
            if(msg.equals("n") || msg.equals("N")){
                System.out.println("안녕히 가십시오");
                break;
            }
            System.out.println("다시 시작합니다. 파이팅!");
        }
    }
}