Home > Enterprise >  java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

Time:12-23

I'm creating a jumbled word game. At first I only have 3 levels, but when I try to add another levels, I got this error " java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 "

This part is where the error

@Override
protected void onResume() {
    super.onResume();
    final String [] str=quesWord.toArray(new String[quesWord.size()]);
    attemptsLeft.setText("Attempts left: " chances);
    points.setText("Score: " score);
    jumbleWord.setText(wordJumble(str[0]));
    b.setOnClickListener(new OnClickListener() {
        int j=0;
        int len=str.length;
public static String wordJumble(String word )
{
    Random random = new Random();
    char wordArray[] = word.toCharArray();
    for(int i=0 ; i< wordArray.length-1 ; i   )
    {
        int j = random.nextInt(wordArray.length-1);
        char temp = wordArray[i];
        wordArray[i] = wordArray[j];
        wordArray[j] = temp;
    }
    if(wordArray.toString().equals(word)){
        wordJumble(word);
    }
    return new String(wordArray);
}
public void fetchWords(){
    try{
        c=db.rawQuery("select * from wordscramble where level='" lv "'",null);
        while(c.moveToNext()){
            s=c.getString(0);
            quesWord.add(s);
        }
        Collections.shuffle(quesWord);
    }
    catch(Exception e){

    }
}

CodePudding user response:

To fix this error, you need to make sure that the array is not empty before trying to access its elements. You can do this by checking the length of the array before attempting to access its elements:

int[] arr = new int[0];
if (arr.length > 0) {
    int firstElement = arr[0];
} else {
    // handle the case where the array is empty
}

Alternatively, you can use a try-catch block to handle the exception when it is thrown:

int[] arr = new int[0];
try {
    int firstElement = arr[0];
} catch (ArrayIndexOutOfBoundsException e) {
    // handle the exception
}

CodePudding user response:

In your wordJumble function replace

for(int i=0 ; i< wordArray.length-1 ; i   )
    {
        int j = random.nextInt(wordArray.length-1);
        char temp = wordArray[i];
        wordArray[i] = wordArray[j];
        wordArray[j] = temp;
    }

with

for(int i=0 ; i< wordArray.length ; i   )
    {
        int j = random.nextInt(wordArray.length-1);
        char temp = wordArray[i];
        wordArray[i] = wordArray[j];
        wordArray[j] = temp;
    }

you are already using < for loop till length-1. No need to specify again length-1 as it will check till second last element.

  • Related