Game game = new Game();
game.play();

 

class Game {
    int randNum;
    int guessNum;
    boolean result;
    int win = 0;
    int lose = 0;

    Scanner sc = new Scanner(System.in);    // 멤버 변수 -> heap 영역에 올라가 있음

    // 주사위의 랜덤 숫자 결정
    void init() {   // initialize (초기화)
        result = false;
        randNum = (int)(Math.random() * 6) + 1;
    }

    // 유저 인풋 받기
    void userInput() {
        // Scanner sc = new Scanner(System.in);     // --> Stack에 올라가 있음
        System.out.print("예측 숫자 입력 >>> ");
        guessNum = sc.nextInt();
    }

    // 판정
    void finding() {
        if (randNum == guessNum) {
            result = true;
            win++;
        } else {
            lose++;
        }
    }
    // 판정 결과
    void result() {
        System.out.println("주사위 수 = " + randNum);
        if (result) {
            System.out.println("정답입니다!");
            System.out.println("승률: " + win + "승" + lose + "패");
        } else {
            System.out.println("틀렸습니다.");
            System.out.println("승률: " + win + "승" + lose + "패");
        }
    }

    void play() {
        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;
            }
        }
    }
}

실행결과

 

+ Recent posts