|
26 | 26 |
|
27 | 27 | package javaexercises.difficult;
|
28 | 28 |
|
| 29 | +import java.util.Random; |
| 30 | +import java.util.Scanner; |
| 31 | + |
29 | 32 | public class WordGuess {
|
30 | 33 |
|
| 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 | + |
31 | 45 | public static void main(String[] args)
|
32 | 46 | {
|
33 | 47 | 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; |
34 | 63 | }
|
35 | 64 |
|
| 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 | + } |
36 | 115 | }
|
0 commit comments