Skip to content

Commit e85d915

Browse files
committed
mouredev#49 - Java
1 parent c027c25 commit e85d915

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import java.security.SecureRandom;
2+
import java.util.Random;
3+
import java.util.Scanner;
4+
5+
public class Main {
6+
7+
private final Random r = new SecureRandom();
8+
private final Scanner sc = new Scanner(System.in);
9+
private final String ALPHABET = "ABC123";
10+
private final int CODE_LENGTH = 4;
11+
private final String secretCode;
12+
13+
public static void main(String[] args) {
14+
Main m = new Main();
15+
m.start();
16+
}
17+
18+
public Main() {
19+
this.secretCode = generateSecretCode();
20+
}
21+
22+
private String generateSecretCode() {
23+
StringBuilder sb = new StringBuilder();
24+
while (sb.length() < CODE_LENGTH) {
25+
char c = ALPHABET.charAt(r.nextInt(ALPHABET.length()));
26+
if (sb.indexOf(String.valueOf(c)) == -1) sb.append(c);
27+
}
28+
29+
return sb.toString();
30+
}
31+
32+
public void start() {
33+
int attempts = 0;
34+
35+
while (attempts < 10) {
36+
System.out.println("Enter a code:");
37+
String code = sc.nextLine();
38+
checkCode(code.toUpperCase());
39+
attempts++;
40+
}
41+
42+
}
43+
44+
public void checkCode(String code) {
45+
if (code.isBlank()) {
46+
System.out.println("Please enter a code");
47+
return;
48+
}
49+
50+
if (code.length() != CODE_LENGTH) {
51+
System.out.println("The code must be 4 characters long");
52+
return;
53+
}
54+
55+
if (code.equals(secretCode)) {
56+
System.out.println("Congratulations! You have guessed the secret code.");
57+
System.exit(0);
58+
}
59+
60+
for (int i = 0; i < CODE_LENGTH; i++) {
61+
char current = code.charAt(i);
62+
63+
if (current == secretCode.charAt(i)) System.out.println("Character " + current + " is in the correct position");
64+
else if (secretCode.indexOf(current) != -1) System.out.println("Character " + current + " is in the secret code, but in the wrong position");
65+
else System.out.println("Character " + current + " is not in the secret code");
66+
}
67+
68+
}
69+
70+
}

0 commit comments

Comments
 (0)