【问题标题】:How do i make the generate button generate the array values at a random order? [closed]如何使生成按钮以随机顺序生成数组值? [关闭]
【发布时间】:2013-10-21 04:28:57
【问题描述】:
import java.util.Random;

public class Generator extends javax.swing.JFrame {

    String[] gamesL = new String[] {"Dota 2", "Garrys mod", "Dungeon Defenders"};

    Random rand = new Random();

    public Generator() {
        initComponents();
    }

private void initComponents() {...}

private void generateActionPerformed(java.awt.event.ActionEvent evt) {                                         
display.setText("You shall play " + gamesL[0]); 
}

【问题讨论】:

  • 从代码 sn-p 看来,OP 想要打乱数组,然后选择第一个元素。但是“可能重复”会导致更好的解决方案,即从 {0,1,2} 中选择一个随机数,然后从数组中取出该元素。

标签: java arrays string random


【解决方案1】:

使用Collections.shuffle(你的arraylist) 得到洗牌后的随机数组; 您需要导入 java.util.Collections。

【讨论】:

    【解决方案2】:

    这会对(字符串)数组(与集合)进行排序

    public void unsortStringArray(String[] a) {
        int len = a.length;
        for(int sourceIdx = 0; sourceIdx<len; sourceIdx++) {
            int destIdx = (int) Math.floor(Math.random() * len);
            String sx = a[destIdx];
            a[destIdx] = a[sourceIdx];
            a[sourceIdx] = sx;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2013-04-15
      • 1970-01-01
      相关资源
      最近更新 更多