Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need help solving string index out of bounds exception

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading