【问题标题】:Make a random array and print it one by one做一个随机数组,一张一张打印出来
【发布时间】:2015-06-10 02:38:15
【问题描述】:

我想制作一个随机数组并一张一张打印出来。但我需要打印所有这些而不做任何重复。我尝试将其添加到列表中,但似乎失败了。

我的代码:

String quest1 = "5x5#5*10#8/4"
String[] quest = quest1.split("#");

ArrayList <String> question = new ArrayList<String>();
question.add(quest[0]);
question.add(quest[1]);
question.add(quest[2]);


Random rand = new Random();
int id = rand.nextInt(question.size());
System.out.println(question.get(id));
question.remove(id);

我想以随机顺序打印 5x5 5*10 8/4,我想打印每一个而不再次打印。

【问题讨论】:

标签: android arrays list random


【解决方案1】:

制作键值二维对象数组或整数和布尔值的哈希图。针对所有数字,将布尔值保持为 false(表示该数字尚未打印)。然后使用 Random 类生成一个随机数。让这成为n。计算 n%array.length。现在看看这个新索引是否在 2dArray/hashmap 中有真/假。如果为假,则打印相应的数字,否则不打印任何内容。我希望你很清楚

【讨论】:

    【解决方案2】:

    试试下面的代码

    ArrayList<Integer> questionPrinted = new ArrayList<Integer>();
            int i=0;
            while (question.size()>0) {
                Random rand = new Random();
                int id = rand.nextInt(question.size());
                if (questionPrinted.size() > 0) {
                    if (questionPrinted.contains(id)) {
                        while (!questionPrinted.contains(id))
                            id = rand.nextInt(question.size());
                    }
                }
                questionPrinted.add(i);
                System.out.println(question.get(id));
                question.remove(id);
                i++;
            }
    

    【讨论】:

    • 纯代码答案没有多大用处。考虑注释掉它的作用和方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2021-11-21
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多