What can I do to fix the java.lang.StringIndexOutOfBoundsException?

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

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() + ".");
 if(phrase.contains(userGuess.toUpperCase())) {

   System.out.println("This is present in the secret phrase.");
   System.out.println("Number of wrong guesses so far: " + wrongGuesses);
   int index = phrase.indexOf(userGuess);
   encodedPhrase = (encodedPhrase.substring(0, index) + userGuess + encodedPhrase.substring(index + 1));


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.

Leave a Reply

Your email address will not be published. Required fields are marked *