본문 바로가기
프로그래밍/자바

자바 숫자야구 소스

by 밍구몬 2019. 3. 7.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.math.*;
import java.util.Scanner;
 
public class NumberBaseball {
 
    static int answer[] = new int[3];
    static int input[] = new int[3];
    static int count = 0;    //몇번만에 성공하였는지 체크하기 위한 변수
    static int strike;
    static int ball;
    
    static void makeAnswer() {        
        
        for(int i=0;i<answer.length;i++) {
            answer[i] = (int)(Math.random()*9+1);    //1~9사이 랜덤 숫자 생성하여 저장
            for(int j=0;j<i;j++) {    //중복 제거
                if(answer[i]==answer[j]) {
                    i--;
                }
            }
        }
        
    }
    
    static void input() {
        
        Scanner s = new Scanner(System.in);
        
        System.out.print("1 ~ 9의 숫자중 세가지를 입력(중복입력x) : ");
        
        for(int i=0;i<input.length;i++) {
            input[i]=s.nextInt();
        }
        
        for(int i=0;i<input.length;i++) {    //똑같은 수를 입력하였는지 체크
            int flag=0;
            for(int j=0;j<i;j++) {
                if(input[i]==input[j]) {
                    System.out.println("중복입력 불가");
                    flag=1;
                    break;
                }
            }
            if(flag==1) {
                break;
            }
        }
        
    }
    
    static boolean compare() {
        
        for(int i=0;i<answer.length;i++) {
            if(answer[i]==input[i]) {    //스트라이크 체크
                strike++;
            }
            for(int j=0;j<answer.length;j++) {    //볼 체크
                if(answer[i]==input[j] && i!=j) {
                    ball++;
                }
            }
        }
        
        if(strike==3) {
            System.out.println(count+"번 홈런!!!!!");
            return false;
        }else {
            System.out.println(count+"번째 : "+strike+"스트라이크, "+ball+"볼");
            return true;    
        }
        
    }
    
    public static void main(String[] args) {
        
        makeAnswer();
        while(compare()) {
            strike=0;
            ball=0;
            input();
            count++;
        }
        
    }
}
 
cs