在Android中从另一个整数[]数组中创建一个随机整数[]数组。

时间:2022-09-25 09:19:00

I am creating an activity that displays 9 images in a GridView. I want those images be selected randomly from an Integer[] array that contains 26 images. So my best approach is setting the 26 images fixed and then created a new array and fill using this simple method:

我正在创建一个在GridView中显示9个图像的活动。我希望从一个包含26个图像的整数[]数组中随机选择这些图像。因此,我的最佳方法是设置26个图像固定,然后创建一个新的数组并使用这个简单的方法填充:

    public Integer [] allLetters = {
             R.drawable.a, R.drawable.b,
             R.drawable.c, R.drawable.d,
             R.drawable.e, R.drawable.f,
             R.drawable.g, R.drawable.h,
             R.drawable.i, R.drawable.j,
             R.drawable.k, R.drawable.l,
             R.drawable.m, R.drawable.m,
             R.drawable.o, R.drawable.p,
             R.drawable.q, R.drawable.r,
             R.drawable.s, R.drawable.t,
             R.drawable.u, R.drawable.v,
             R.drawable.w, R.drawable.x,
             R.drawable.y, R.drawable.z
    };
    private Integer[] randomLetters=null;
    public int index=0;
    public Random r= new Random();
    public void creaArray() {
        for (int i = 0; i < 9; i++){
            index=r.nextInt(26);
            randomLetters[i]=allLetters[index];
        }
    }

I thought this would fill randomLetters with 9 random values from allLetters but the app is "forced closing" me :( Any ideas?

我想这可以用allLetters中的9个随机值来填充随机值,但是这个应用程序是“强制关闭”我的:(有什么想法吗?

1 个解决方案

#1


0  

It crashes because you have not initialized the integer array. You must do something like this:

它崩溃是因为没有初始化整数数组。你必须这样做:

private Integer[] randomLetters = new Integer[9];

Bear in mind that your current algorithm could repeat some of the letters, which sometimes is an undesirable behavior.

记住,你当前的算法可以重复某些字母,有时是不可取的行为。

Also, ready about how to use adb logcat in order to detect problems like this. You will save you and us a lot time.

同时,准备好如何使用adb logcat来检测此类问题。你会节省很多时间。

#1


0  

It crashes because you have not initialized the integer array. You must do something like this:

它崩溃是因为没有初始化整数数组。你必须这样做:

private Integer[] randomLetters = new Integer[9];

Bear in mind that your current algorithm could repeat some of the letters, which sometimes is an undesirable behavior.

记住,你当前的算法可以重复某些字母,有时是不可取的行为。

Also, ready about how to use adb logcat in order to detect problems like this. You will save you and us a lot time.

同时,准备好如何使用adb logcat来检测此类问题。你会节省很多时间。