user1104939
user1104939

Reputation: 1425

Strange java.lang.ArrayIndexOutOfBoundsException

I have a strange problem in my application

Some users send me the error:

java.lang.ArrayIndexOutOfBoundsException

i , myself , have never experienced that error. Here is the code:

         for(int i =0; i<length*2; i+=2) {
            if(charsLeft[i/2]==1)
                temp[i]=word[i/2];//IT HAPPENS HERE
        ....

        length = word.length;        
        charsLeft = new int[length];
        temp = new String[length*2];

When a users goes back to home screen , the application saves and later loads the data this way:

    public Bundle saveState(Bundle bundle) {
    synchronized (surfaceHolder) {
        if (bundle != null) {
            bundle.putStringArray("word",game.word.word);
            bundle.putIntArray("charsLeft",game.word.charsLeft);
            bundle.putInt("length",game.word.word().length());
            bundle.putStringArray("temp",game.word.temp);
            bundle.putCharArray("characters", game.word.characters);
            ...                     
        }
    }
    return bundle;
}
public synchronized void restoreState(Bundle bundle) {
    synchronized (surfaceHolder) {
        mPaused = true;
        if (bundle != null) {       
            game.word.word = bundle.getStringArray("word");
            game.word.length = bundle.getInt("length");
            game.word.init();
            game.word.charsLeft = bundle.getIntArray("charsLeft");              
            game.word.temp = bundle.getStringArray("temp");
            game.word.characters = bundle.getCharArray("characters");
            ...     

        }            
     }
}

Does anyone see where it goe

EDIT full loop

 for(int i =0; i<(length)*2; i+=2) {
            if(charsLeft[i/2]==1)
                temp[i]=word[i/2];
            else
                temp[i]="_";
            temp[i+1]=" ";
            }     

Example word[0] = a word[1] = n ..... ->"answer" the loop diveds the word in spaces and the letter or if the letter isnt guessed yet by a _ ex. a n s _ e _

EDIT: I think I found the error : A thread was calling the loop while an other thread could reassign word to another value , and if the loop was called before the value of length was changed then you have an error. I changed the loop to this

     temp = new String[word.length*2];
     for(int i =0; i<(word.length*2); i+=2) {
            if(charsLeft[i/2]==1)
                temp[i]=word[i/2];

Now lets hope its fixed

Upvotes: 0

Views: 241

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38706

Forget your loop if all you want to do is divide the word by spaces or blanks. Just using split:

String[] words = word.split( "\s|_" );

That will spit the word into an array of words on either a space or an underscore.

Upvotes: 2

Related Questions