【问题标题】:Android: Check Array for a number RandomAndroid:检查数组中的数字随机
【发布时间】:2015-03-10 14:40:46
【问题描述】:

我希望你能帮助我。

我制作了一个像 4Pics1Word 这样的游戏。

我想随机加载关卡,我想要一个循环,生成一个从 0 到 10 的随机数,然后检查生成的数字是否是第一次加载。 如果是,则将其写入数组并结束循环。 如果该数字不是第一次加载,则生成一个新的随机数并再次检查,直到没有使用为止。

例如,这是我的代码(不能正常工作):

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: 谢谢大家,我认为Oren的解决方案是最好的

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

但是如果我关闭游戏如何保存列表呢?

【问题讨论】:

    标签: android arrays random find


    【解决方案1】:

    您最好创建一个您想要的号码列表,然后在该列表上调用Collections.shuffle()

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

    【讨论】:

      【解决方案2】:
          int oldnumber = 5;
          int newnumber = new Random().nextInt(10);
          while (newnumber == oldnumber){
              newnumber = new Random().nextInt(10);
          }
      

      【讨论】:

        猜你喜欢
        • 2017-09-15
        • 1970-01-01
        • 2018-10-09
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2014-05-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多