I’m writing a hangman (the game) program, and I have an encoded phrase that is shown as asterisks to the user. When the user guesses a correct letter, I’m trying to change the encoded asterisks phrase so that it changes the one asterisk to the the user input letter. I’m using the indexOf method, but it keeps outputting a -1 and giving me the
java.lang.StringIndexOutOfBoundsException String index out of range -1
Here is the code:
System.out.print("Enter your next guess: "); String userGuess = keyboard.nextLine(); System.out.println("You guessed " + userGuess.toUpperCase() + "."); System.out.println(); if(phrase.contains(userGuess.toUpperCase())) { System.out.println("This is present in the secret phrase."); System.out.println(); System.out.println("Number of wrong guesses so far: " + wrongGuesses); int index = phrase.indexOf(userGuess); System.out.print(index); encodedPhrase = (encodedPhrase.substring(0, index) + userGuess + encodedPhrase.substring(index + 1));
Answer
Just because the string contains userGuess.toUpperCase()
that doesn’t mean it contains userGuess
too. You’ll get -1 when it doesn’t.
A simple fix:
String userGuess = keyboard.nextLine().toUpperCase();
And then you can remove all the other .toUpperCase()
calls, as the string is already uppercased, once and for all.