开发者

Randomly selected index in integer array causing crash

This should be a simple fix but I just cant get it?!

I want to randomly select an integer from an integer array and load a bitmap of it - sometimes it goes thru but most of the time it errors out - i don't see how I'm going outside of the array?

At first I used array.length() and then array.length() - 1, but now I'm using a range safetly between the start and end ~ which is not what I want to do

    public int GetRandomNumber(int min, int ma开发者_如何学Pythonx) {
    return min + (int)(Math.random() * ((max - min) + 1));
}

public void Whatever()
{

    Integer[] ImageIds;
    ImageIds = new Integer[9];
    ImageIds[0] = R.drawable.splatter1;
    ImageIds[1] = R.drawable.splatter2;
    ImageIds[2] = R.drawable.splatter3;
    ImageIds[3] = R.drawable.splatter4;
    ImageIds[4] = R.drawable.splatter5;
    ImageIds[5] = R.drawable.splatter6;
    ImageIds[6] = R.drawable.splatter7;
    ImageIds[7] = R.drawable.splatter8;
    ImageIds[8] = R.drawable.splatter9;
    ImageIds[9] = R.drawable.splatter10;

Bitmap Asset;

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

        int RandomIndex = GetRandomNumber(0, 9);

        Asset = BitmapFactory.decodeResource(mContext.getResources(), ImageIds[RandomIndex ]);

     }
 }

I get an ArrayIndexOutOfBounds exception

Why does this crash?


Because must be

ImageIds = new Integer[10];

You set 10 images, but create array of size 9. Also look at line in logs, which caused error. It really helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜