-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathNumberBaseball.java
More file actions
76 lines (65 loc) · 2.21 KB
/
NumberBaseball.java
File metadata and controls
76 lines (65 loc) · 2.21 KB
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
import java.util.Random;
import java.util.Scanner;
public class NumberBaseball {
public static int SIZE = 3;
public static Boolean status = true;
public static int[] answer = new int[SIZE];
public static int[] guess = new int[SIZE];
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
setAnswer();
while (status) {
System.out.print("숫자를 입력해주세요 : ");
int inputNumber = sc.nextInt();
setGuess(inputNumber);
status = checkGuess();
}
}
public static void setAnswer() {
while (true) {
Random random = new Random();
answer[0] = random.nextInt(9) + 1;
answer[1] = random.nextInt(9) + 1;
answer[2] = random.nextInt(9) + 1;
if (answer[0] != answer[1] && answer[1] != answer[2] && answer[2] != answer[0]) break;
}
}
public static void setGuess(int inputNumber) {
guess[0] = inputNumber / 100;
guess[1] = inputNumber % 100 / 10;
guess[2] = inputNumber % 10;
}
public static boolean checkGuess() {
int result = checkSingleDigit(0) + checkSingleDigit(1) + checkSingleDigit(2);
System.out.println(createMessage(result));
if (result == 30) {
return isRestart(sc.nextInt());
}
return true;
}
public static String createMessage(int result) {
if (result == 30) {
return "3개의 숫자를 모두 맞히셨습니다! 게임 종료\n게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.";
}
if (result != 0) {
return String.format("%d 스트라이크 %d 볼", result / 10, result % 10);
}
return "낫싱";
}
public static int checkSingleDigit(int idx) {
if (answer[idx] == guess[idx]) {
return 10;
}
if (answer[(idx + 1) % 3] == guess[idx] || answer[(idx + 2) % 3] == guess[idx]) {
return 1;
}
return 0;
}
public static boolean isRestart(int restart) {
if (restart == 1) {
setAnswer();
return true;
}
return false;
}
}