I need to check if the user-input letter, along with the spaces they guess, is at a specific spot on the hidden word.
the variable one is equal to the space index the user guessed.. and letterGuess is the letter they guessed. How is my code wrong??
example: secret word is hello
hidden word is == -----
user guesses h 0 1 2 3
so, it needs to check if the spaces at indexes 0 1 2 3 at the word hello contain the user guessed "h"
if so, need to replace ----- to h---- .
String firstSpace = guessedSpaces.substring(0,1);
String secondSpace = guessedSpaces.substring(2,3);
String thirdSpace = guessedSpaces.substring(4,5);
String fourthSpace = guessedSpaces.substring(6,7);
int one = Integer.parseInt(firstSpace);
int two = Integer.parseInt(secondSpace);
int three = Integer.parseInt(thirdSpace);
int four = Integer.parseInt(fourthSpace);
(secretWord.charAt(one)==letterGuess)
(secretWord.charAt(one)==letterGuess)
(secretWord.charAt(one)==letterGuess)
(secretWord.charAt(one)==letterGuess)
解决方案
Here's a brief amount of code that is a complete hangman program:
static int MAX_MISSES = 5;
static String[] WORDS = { "QUICK", "BROWN", "JUMPS" }; // etc
public static void main(String[] args) throws Exception {
String word = WORDS[new Random().nextInt(WORDS.length)], guesses = " ";
int misses = -1;
for (Scanner in = new Scanner(System.in); !word.matches("[" + guesses + "]+") & (misses += word.contains(guesses.substring(0, 1)) ? 0 : 1) <= MAX_MISSES; guesses = in.nextLine().toUpperCase().charAt(0) + guesses)
System.out.println(word.replaceAll("(?<=.)", " ").replaceAll("[^" + guesses + "]", "_"));
System.out.println(word + (misses > MAX_MISSES ? " not" : "") + " solved with " + misses + " incorrect guesses");
}
Some notes:
Regex is used to both check for solution and display the current guess status
& is used instead of && in the loop termination to force both sides of the logic to be executed - thus always updating the misses correctly
Various other tricks have been used to deliberately increase code density
There is no error checking for input. If more than one letter is input by the user, only the first is used. If no letters are input, it will explode. Error checking could be added without adding much more code, but the for line would be a whopper - I leave that as an exercise for the reader.
Also, there is no checking for erroneously guessing the same letter multiple times. With this code, if you guess a correct letter twice, nothing bad happens, but if you guess a wrong letter twice, it counts as a separate "miss", so you'll burn one of your chances.