Skip to content

Commit 8507562

Browse files
author
java-tester-x
committed
add solution of "WordGuess" task
add solution of "WordGuess" task
1 parent dee2478 commit 8507562

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

difficult/WordGuess.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,90 @@
2626

2727
package javaexercises.difficult;
2828

29+
import java.util.Random;
30+
import java.util.Scanner;
31+
2932
public class WordGuess {
3033

34+
private final String[] words = {
35+
"testing", "hello", "world", "template", "java"
36+
, "maining", "computer", "processor", "univercity"
37+
, "boolean", "string", "integer", "character"
38+
, "indicator", "controller", "model", "view"
39+
};
40+
41+
private String secretWord;
42+
43+
private boolean[] secretWordMatches;
44+
3145
public static void main(String[] args)
3246
{
3347
WordGuess aWordGuess = new WordGuess();
48+
aWordGuess.setSecretWord();
49+
aWordGuess.runGame();
50+
}
51+
52+
private void setSecretWord(String word) {
53+
secretWord = word;
54+
}
55+
56+
private void setSecretWord() {
57+
Random rand = new Random();
58+
secretWord = words[rand.nextInt(words.length-1)];
59+
}
60+
61+
private String getSecretWord() {
62+
return secretWord;
3463
}
3564

65+
private String getTrialWordWithMatches()
66+
{
67+
StringBuilder str = new StringBuilder();
68+
for (int i = 0; i < secretWord.length(); i++) {
69+
str.append( (secretWordMatches[i] ? secretWord.charAt(i) : '_') );
70+
}
71+
return str.toString();
72+
}
73+
74+
75+
private void checkTrialWord(char ch)
76+
{
77+
for (int i = 0; i < secretWord.length(); i++)
78+
{
79+
if (secretWordMatches[i]) {
80+
continue;
81+
}
82+
secretWordMatches[i] = secretWord.charAt(i) == ch;
83+
}
84+
}
85+
86+
private void runGame()
87+
{
88+
Scanner in = new Scanner(System.in);
89+
secretWordMatches = new boolean[secretWord.length()];
90+
int trials = 0;
91+
while (true) {
92+
System.out.print("Key in one character or your guess word: ");
93+
String trialWord = (in.hasNext()) ? in.next() : "";
94+
95+
trials++;
96+
97+
if (trialWord.length() < 1) {
98+
continue;
99+
}
100+
101+
if (trialWord.length() == 1) {
102+
checkTrialWord(trialWord.charAt(0));
103+
trialWord = getTrialWordWithMatches();
104+
System.out.printf("Trail %1$d: %2$s\n", trials, trialWord);
105+
106+
}
107+
108+
if (trialWord.equals(secretWord)) {
109+
System.out.printf("Trail %d: Congratulation!\n", trials);
110+
break;
111+
}
112+
}
113+
System.out.printf("You got in %d trials\n", trials);
114+
}
36115
}

0 commit comments

Comments
 (0)