android 数组索引越界异常:长度= 0;索引= 0 [重复]

nle07wnf  于 2022-12-25  发布在  Android
关注(0)|答案(2)|浏览(212)
    • 此问题在此处已有答案**:

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?(26个答案)
昨天关门了。
我正在创建一个杂乱的文字游戏。起初我只有3个级别,但当我尝试添加其他级别时,我收到了这个错误"java. lang. ArrayIndexOutOfBoundsException:长度= 0;索引= 0 "
这部分是错误所在

@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){

    }
}
6rvt4ljy

6rvt4ljy1#

若要修复此错误,您需要确保在尝试访问数组元素之前数组不为空。您可以通过在尝试访问数组元素之前检查数组长度来实现此目的:

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

或者,您可以使用try-catch块来处理抛出的异常:

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

c3frrgcw2#

在wordJumble函数中替换

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;
    }

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;
    }

你已经在使用〈for循环直到length-1。2不需要再指定length-1,因为它会检查到倒数第二个元素。

相关问题