安卓:检查数组的一个随机数 [英] Android: Check Array for a number Random

查看:259
本文介绍了安卓:检查数组的一个随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望你能帮助我。

我作出这样4Pics1Word游戏。

I make a game like 4Pics1Word.

我要随机加载水平,我想一个循环产生从0到10的随机数,然后检查生成的编号是第一次加载。
如果是写在一个数组中,并结束循环。
如果该号码不是第一次加载,产生一个新的随机数,然后再次检查,直到不使用它。

I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded. If yes write it in an array and end the loop. If the number is not the first time loaded, generate a new random number and check it again until it is not used.

例如,这是我的code(鸵鸟政策工作的权利):

For example this is my code (don´t work right):

Boolean usedImageSet = false;
    for (int t = 0; t <= usedImages.length; t++) {
        if (usedImageSet == false) {
            StringBuilder sb = new StringBuilder();
            sb.append(currentQuestion);
            String used = sb.toString();            

            if (usedImages[t] != null) {
                System.out.println("usedImage" + t
                        + " = not Null, it is" + usedImages[t]);
                if (usedImages[t].equals(used)) {
                    System.out.println("String: "
                            + used
                            + " found it here: [" + t + "]");
                    currentQuestion = (int) (Math.random() * 10);

                }else {
                    System.out.println("String: "
                            + used + " not found");
                }
            }
            if (usedImages[t] == null) {
                usedImages[t] = used;
                System.out.println("useddImage[" + t + "]: "
                        + usedImages[t]);
                System.out.println("usedImage" + t + " is Null, change to"
                        + usedImages[t]);
                usedImageSet = true;
            }
        }

    }

PS:
谢谢大家,我想从奥伦的解决方案是最好的。

PS: Thank you all, I think the solution from Oren is the best

    // naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
    list.add(i);
}
Collections.shuffle(list);

// output the generated list
for(int i=0; i<10; i++)
{
    System.out.print(list.get(i));
}

但我怎么能保存列表,如果我关闭游戏?

But how can I save the list if I close the game?

推荐答案

您可能会好得多创造你想要的号码列表,然后调用的 Col​​lections.shuffle()名单上

You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.

// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
    list.add(i);
}
Collections.shuffle(list);

// output the generated list
for(int i=0; i<10; i++)
{
    System.out.print(list.get(i));
}

这篇关于安卓:检查数组的一个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆