[英]Randomizing an array of string without repetitions
因此,我遇到了一個小問題:我想將一個字符串數組隨機化而不重復。 我已經搜索過這種東西,並且發現了一些“無重復地隨機化數組”,但是我所能找到的只是關於隨機化一個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[]
數組更大,並且可能會變得更大,因此我考慮了一種使randomizer易於擴展的方法...
我嘗試了諸如Collection
和ArrayList
東西(或類似的東西),但沒有找到想要的結果。
快速注釋2:如果我的問題不太清楚,或者您想讓我在代碼中或其他內容中添加更多有關變量的詳細信息,請告訴我,我將對其進行編輯。
快速注釋3(這么多快速注釋!):我對編程有點陌生。 結果,我寧願使用for()
循環, Arrays
, if()
,如果可能的else if
使用else if
。 但是任何不重復一組字符串的隨機化方式都會讓我感到高興...
非常感謝!
如果要allCommands
數組allCommands
,可以采用幾種方法。 這是一個使用Collections.shuffle()
和Arrays.asList()
來隨機播放allCommands
支持的List
的allCommands
,-
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.