java - 随机化字符串数组而不重复

标签 java arrays string random

所以我遇到了一个小问题:我想随机化一个字符串数组而不进行任何重复。我已经搜索过这样的东西,并且我发现了一些“随机化一个没有重复的数组”,但我所能找到的只是随机化一个int数组,它没有给我我想要的结果。

这是我的代码(我缩短了一点以仅显示有用的部分),以便你们可以帮助我使用我自己的代码。我想要随机化的数组是 allCommands[] 数组。无论如何,这就是:

 Box box = Box.createVerticalBox();

        String[] allCommands = new String[]{"start", "help", "hint", "look around", "take note",
                "look under bed"};

        JLabel[] fun = new JLabel[allCommands.length];

        for(int o = 0 ; o < allCommands.length ; o++){

            fun[o] = new JLabel(allCommands[o]);

            box.add(fun[o]);

        }

快速说明:我的代码中的 allCommands[] 数组要大得多,我可能会让它更大,所以我考虑了一种使随机化器易于扩展的方法...
我尝试了 CollectionArrayList (或类似的东西),但没有找到我想要的结果。

快速说明 #2:如果我的问题不是很清楚,或者您希望我在代码或其他内容中添加有关变量的更多详细信息,请告诉我,我会将其编辑掉。

快速注释#3(这么多快速注释!):我对编程有点陌生。因此,我更喜欢使用 for() 循环、Arraysif()else if if可能的。但是任何不重复字符串数组的随机化方法都会让我高兴......

非常感谢!

最佳答案

如果你想打乱数组allCommands,有多种方法可以实现。这是使用 Collections.shuffle() 的一个和 Arrays.asList()随机播放由 allCommands 支持的 List,-

String[] allCommands = new String[] { "start",
    "help", "hint", "look around", "take note",
    "look under bed" };
System.out.println(Arrays.toString(allCommands));
Collections.shuffle(Arrays.asList(allCommands)); // <-- shuffles allCommands
System.out.println(Arrays.toString(allCommands));

关于java - 随机化字符串数组而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473099/

相关文章:

java - 返回未找到方法的错误响应正文 - Spring Rest WebService

java - 扩展 AbstractTableModel 并动态填充 jTable

java - RadixSort 算法运行时

php - 如果和空行为古怪

java - 在 NumberPicker 中设置数字的默认值

java - Thymeleaf#numbers.formatInteger 奇怪的行为

java - Rational Appln Deb IBM 7.5.4

c++ - 反向数组 - 没有第一个数字

javascript - 检查数组中的字符串时如何删除区分大小写?

Java 从字符串中删除/删除多个单词