Question

I am making a hangman game for my ap computer science class and could not seem to figure out how to fix my problem with the strings. I am getting an out of bounds index error. it says

java.lang.StringIndexOutOfBoundsException: String index out of range: 7

occurring here:

if(theGuess.equals(wordToGuess.substring(i,i+1)))

Here is the program code if it is any help.

import javax.swing.JOptionPane; 
public class Hangman extends BasicGame
{
    private final String WORDCHOICES= "apple"+"great"+"zebra"+"mouse"+"chick"+"class"+"abhor"+"abide"
        +"fuzzy"+"brute"+"blunt"+"comic"+"cater"+"stone"+"chaos"+"dufus"+"earth"+"decal"+"happy"+"heist"
        +"idler"+"lions"+"hates"+"idols"+"lasso"+"lives"+"lisps"+"major"+"mound"+"mango"+"meter"+"mercy"
        +"marry"+"pilot"+"plots"+"pants"+"overt"+"quack"+"paver"+"polls"+"scorn"+"sapid"+"sails"+"rowdy"
        +"seeks"+"leech"+"seats"+"spade"+"shoes"+"slurp";
    private String wordToGuess;
    private java.util.Random randy;

    private int wordNum;
    private int numCorrect=0;
    private String[] correctLetters= new String[]{"","","","",""};
    HangDraw artist= new HangDraw();
    public Hangman()
    {
        super();
        randy= new java.util.Random();
        for(int i = 0; i<5;i++)
            correctLetters[i]=null;
        wordNum=0;
        numCorrect=0;
        artist.setUp();
    }
    public void guess()
    {
        wordNum= 5*randy.nextInt(50);
        numCorrect=0;
        int wrong=0;
        String userGuess="";
        int partsDrawn=0;
        wordToGuess=WORDCHOICES.substring(wordNum,wordNum+5)+" ";
        while(numCorrect<5&& partsDrawn<5)
        {
            userGuess= JOptionPane.showInputDialog("Guess a letter, so far you have: "+ correctLetters[0]+
                        correctLetters[1]+correctLetters[2]+correctLetters[3]+correctLetters[4]);

            if(checkLetter(userGuess))
            {
                JOptionPane.showMessageDialog(null, "Correct Guess");
                //print the letter
            }
            else
            {
                //draw the part of the body
                JOptionPane.showMessageDialog(null,"incorrect");
                partsDrawn++;
                artist.drawParts(partsDrawn);
            }
        }
        if(partsDrawn==5)
        {
            JOptionPane.showMessageDialog(null, "failed to guess, the word is: "+wordToGuess);
        }
        else
        {
            JOptionPane.showMessageDialog(null, "correct, the word was: "+ wordToGuess);
        }
    }

    private boolean checkLetter(String theGuess)
    {
        boolean matches=false;
        for(int i=0;i<wordToGuess.length();i++)
        {
            if(theGuess.equals(wordToGuess.substring(i,i+1)))
            {
                correctLetters[i]=theGuess;
                matches=true;
                numCorrect++;
            }
        }
        return matches;
    }

}

Thank you for any help you provide

Était-ce utile?

La solution 3

Because you are out of range obviously. you cannot substring from end of string.

for(int i=0;i<wordToGuess.length();i++)
{
    if(theGuess.equals(wordToGuess.substring(i,i+1)))
    {
        correctLetters[i]=theGuess;
        matches=true;
        numCorrect++;
    }
}

Fastest way to find out is to debug the app

Autres conseils

According to the java docs, String#substring throws an IndexOutOfBoundsException

if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

On the last iteration of your loop, i will equal the length of the string, and i+1 is greater than the length of the string, hence the exception.

So you need to change:

for(int i=0;i<=wordToGuess.length();i++)

to

for(int i=0;i<wordToGuess.length();i++)
            ^^^

Your loop is for(int i=0;i<=wordToGuess.length();i++)

Lets assume a simple example, wordToGuess="ABC"

The loop generates values for i=0 to i<=3.

For i=0 you select the first character, for i=1 the second, for i=2 the third, i=3 makes no sense.

Thus use for(int i=0;i<wordToGuess.length();i++)

Core Java is awesome at telling you what is wrong. You stated if(theGuess.equals(wordToGuess.substring(i,i+1))) is throwing the IndexOutOfBoundsException? That means wordToGuess length is less than one character (i.e. the empty string). Basically you are getting attempting to get a substring of length 1 [i,i+1).

Because you are student and I think it's important to work through these yourself, I'm just going to give you a hint: Look at the for loop condition. Also, step through the code with a debugger, or at least put some System.out.println(wordToGuess) statements in to see what the values are.

The problem is that you are out-of-bounds in the preceding for loop: for(int i=0;i<=wordToGuess.length();i++). This will loop past the end of the available characters in the string. Noting that you are using a substring function which uses endpoint notation, the latter endpoint must be within the bounds of the string and so this loop should be specified as for(int i=0;i<wordToGuess.length();i++). This will ensure that the last iteration does not invoke the IndexOutOfBoundsError.

Change your condition in a for loop from i<=wordToGuess.length(), to i<wordToGuess.length(), because now your loop comes to the moment, when i becomes the last element, so the i+1 naturally points "out of bounds".

make following changes

for(int i=0;i<wordToGuess.length();i++)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top