This repository was archived by the owner on Feb 9, 2026. It is now read-only.
forked from next-step/java-baseball-playground
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathComputer.java
More file actions
90 lines (68 loc) · 2.35 KB
/
Computer.java
File metadata and controls
90 lines (68 loc) · 2.35 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
77
78
79
80
81
82
83
84
85
86
87
88
89
package baseball.model;
import java.util.HashMap;
import java.util.Random;
public class Computer {
private final HashMap<Integer, Integer> answer;
public Computer() {
this.answer = createAnswer();
}
public Computer newGame() {
return new Computer();
}
public HashMap<Integer, Integer> createAnswer() {
HashMap<Integer, Integer> answer = new HashMap<>();
int NUMBER_SPACE_SIZE = 3;
while (answer.size() < NUMBER_SPACE_SIZE) {
int randomNumber = getRandomNumber();
if (answer.containsKey(randomNumber)) {
continue;
}
answer.put(randomNumber, answer.size() + 1);
}
return answer;
}
public int[] calculationStrikeAndBall(HashMap<Integer, Integer> answer, String userNumber) {
int strike = 0;
int ball = 0;
for (int i = 0; i < userNumber.length(); i++) {
int digit = Character.getNumericValue(userNumber.charAt(i));
Integer answerValue = answer.get(digit);
if (answerValue != null) {
if (answerValue.equals(i + 1)) {
strike++;
} else {
ball++;
}
}
}
return new int[]{strike, ball};
}
public boolean validationStrikeAndBall(HashMap<Integer, Integer> answer, String userNumber) {
int[] strikeAndBall = calculationStrikeAndBall(answer, userNumber);
int strike = strikeAndBall[0];
int ball = strikeAndBall[1];
if (strike == 3) {
System.out.println("정답입니다.");
}
if (strike == 0 && ball == 0) {
System.out.println("낫씽");
}
if (strike > 0 && ball == 0) {
System.out.printf("%s 스트라이크%s", strike, System.lineSeparator());
}
if (strike == 0 && ball > 0) {
System.out.printf("%s 볼%s", ball, System.lineSeparator());
}
if (strike > 0 && ball > 0) {
System.out.printf("%s 스트라이크, %s 볼%s", strike, ball, System.lineSeparator());
}
return strike == 3;
}
public int getRandomNumber() {
Random random = new Random();
return random.nextInt(9) + 1;
}
public HashMap<Integer, Integer> getAnswer() {
return answer;
}
}