java 숫자야구

cornpip·2023년 6월 14일
1
post-thumbnail

숫자 야구

컴퓨터가 숫자를 생성하였습니다. 답을 맞춰보세요!
1번째 시도 : 134
0B0S
2번째 시도 : 238
1B1S
3번째 시도 : 820
2B1S
4번째 시도 : 028
3B
5번째 시도 : 280
3S
4번만에 맞히셨습니다. 
게임을 종료합니다.

위와 같이 동작하면 성공이다.

public class Baseball {
    static String[] ans = init_Game();

    public static void main(String[] args) throws IOException {
        System.out.println("컴퓨터가 숫자를 생성하였습니다. 답을 맞춰보세요!");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int count = 0;
        while (true) {
            count++;
            System.out.printf("%d번째 시도 : ", count);
            String user_predict = br.readLine();
            String result = play(user_predict);
            System.out.println(result);
            if("3S".equals(result)){
                System.out.println(String.format("%d번만에 맞히셨습니다.\n게임을 종료합니다.", count));
                break;
            }
        }
    }
    static String[] init_Game() {
        String[] result_arr = new String[3];
        int idx = 0, flag = 0;
        t1 : while (idx < 3) {
//            System.out.println(Arrays.toString(result_arr));
            String i = String.valueOf((int) (Math.random() * 10));
            for(String j: result_arr){
                if(Objects.equals(i, j)) continue t1;
            }
            result_arr[idx++] = i;
        }
        System.out.println(Arrays.toString(result_arr));
        return result_arr;
    }

    static String play(String user_predict) {
        int b_count = 0, s_count = 0;
        String[] predict_arr = user_predict.split("");
        for(int i=0; i<3; i++){
            for(int j=0; j<3; j++){
                if(Objects.equals(predict_arr[i], ans[j])){
                    if( Objects.equals(i, j)) s_count++;
                    else b_count++;
                }
            }
        }
        if(b_count == 0) return String.format("%dS", s_count);
        if(s_count == 0) return String.format("%dB", b_count);
        return String.format("%dB%dS", b_count, s_count);
    }
}

initGame()으로 정답을 초기화하고 play()로 유저의 예측에 대해 결과를 반환한다. 결과가 3S가 나오면 게임은 종료된다. 입력을 검증하는 과정은 없으므로 정해진대로만 진행한다.^~^

profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

1개의 댓글

comment-user-thumbnail
2023년 6월 15일

우와...

답글 달기
Powered by GraphCDN, the GraphQL CDN