do {
userInput = input.nextLine().toUpperCase(); // Convert input to uppercase to match secretWord's case
if (userInput.length() > 5) {
System.out.println("Invalid Guess, word is too long");
} else if (userInput.length() < 5) {
System.out.println("Invalid Guess, word is too short");
} else {
for (int i = 0; i < 5; i++) {
String userChar = userInput.substring(i, i + 1);
String secretChar = secretWord.substring(i, i + 1);
if (userChar.equals(secretChar)) {
System.out.print(GREEN + userChar + RESET);
} else if (secretWord.contains(userChar)) {
System.out.print(YELLOW + userChar + RESET);
} else {
System.out.print(RED + userChar + RESET);
}
}
System.out.println();
if (userInput.equals(secretWord)) {
correct = true;
}
guessCounter++;
}
} while (guessCounter < maxGuess && !correct);
程序首先从单词数组中选择一个单词。假设从数组中选择的单词是 Brain,如果用户输入 iiii,它将显示前 3 个为黄色,第 4 个为绿色,第 5 个为黄色。我需要它以红色显示除第四个字母之外的所有字母,以表明这些字母不在单词中。
我尝试获取 userChar 的索引并将其与 SecretChar 的索引进行比较,这会导致同样的事情发生。有没有办法我可以使用像 SecretWord.contains(userChar) 这样的东西来确定它应该是红色的?任何帮助将不胜感激!
标记黄色字母时,您需要跟踪哪些字母已经“声明”为黄色或绿色。一种方法是保留可用字符的列表(或多集)并在声明字母时将其清空。您还必须提前仔细检查,确保自己没有偷果岭。我认为最简单的方法是运行该单词两次,首先声明绿色字母,然后再次打印:
List<Character> available = IntStream.range(0, 5)
.filter(i -> secretWord.charAt(i) != userInput.charAt(i))
.map(secretWord::charAt)
.collect(Collectors.toCollection(ArrayList::new));
for (int i = 0; i < 5; i++) {
char userChar = userInput.charAt(i);
char secretChar = secretWord.charAt(i);
if (userChar == secretChar) {
System.out.print(GREEN + userChar + RESET);
} else if (available.remove(userChar)) {
System.out.print(YELLOW + userChar + RESET);
} else {
System.out.print(RED + userChar + RESET);
}
...