Home > front end >  I need help solving string index out of bounds exception
I need help solving string index out of bounds exception

Time:12-17

I'm making some methods for a hangman game for class. I'm trying to make an updated clue that shows the letters that were guessed correctly. Whenever I run the program I get a string index out of bounds exception and I don't know how to fix it. Please help.

 private String makeClue( String word )
    {
        int length = word.length();
        String clue = "";
        for(int i = 0; i < length ; i  )
        {
            clue  = ("_ ");
        }
        return clue;
    }
        
    }
    
    private String updateClue( String clue, String word, String letter )
    {
        String update = " ";
        char guess = letter.charAt(0);
        int l = word.length();
        for(int i = 0; i <= l; i  )
        {
            if(word.charAt(i) == guess)
            {
                update = update   guess;
            }
            else
            {
                int index = i * 2;
                char thing = clue.charAt(index);
                update = update   thing;
            }
            
        }

this is the error that I get: [1]: https://i.stack.imgur.com/k5ilx.png

CodePudding user response:

for(int i = 0; i <= l; i  )
{
    if(word.charAt(i) == guess)

when i is equal to l, i will be the length of word, and word.charAt(i) will be out of bounds (since the index (i) in this function is 0 based)

To understand better

String test = "a";
char c1 = test.charAt(0); // this will be "a"
char c2 = test.charAt(1); // this is out of bounds - there's no character after "a"
  •  Tags:  
  • java
  • Related