【问题标题】:ArrayList and DoublesArrayList 和双打
【发布时间】:2013-10-22 20:39:49
【问题描述】:

我有一个 BINGO 游戏,它有一个充当呼叫者的按钮。每次单击按钮时,我都想要一个介于 1-75 之间的随机数字。 我有以下代码来尝试消除重复项,但我不知道如何从这里继续。我基本上需要在下次单击按钮时从 ArrayList 中删除数字。

private JButton c; {
    c = new JButton("Call");
    c.addActionListener(
        new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             List<Integer> list = new ArrayList<Integer>();
                for(int i = 1; i <= 75; i++){
                    list.add(i);
                }

                Collections.shuffle(list);

【问题讨论】:

  • 您真的想在每次按下按钮时随机播放吗?如果我没有遗漏什么,我认为您可以在每次开始新游戏时随机播放一次,然后只需设置一个索引,每次按下按钮时都会遍历列表。
  • ajb 说得对;一旦列表被洗牌,只需按原样使用(已经随机化的)列表。为此,您需要将初始化和 .shuffle() 调用移出 actionPerformed() 代码

标签: java random arraylist


【解决方案1】:

我会使用 LinkedList 而不是 Arraylist,在构造函数中填充它,然后让 LinkedList 为您完成所有工作。比如:

public class Bingo extends JPanel{
  private static final long serialVersionUID = -5791572059409665801L;
  private LinkedList<Integer> list = new LinkedList<Integer>();
  private JButton c = new JButton("Call");

  public Bingo(){
    for(int ii=1; ii<= 75; ii++)
      list.add(ii);
    Collections.shuffle(list);

    c.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e){
        System.out.println(list.poll());
      }
    });

    add(c);
  }

  private static void createAndShowGUI() {
    JFrame frame = new JFrame("ButtonDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Bingo bingoClass = new Bingo();
    bingoClass.setOpaque(true);
    frame.setContentPane(bingoClass);

    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String... args){
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

【讨论】:

  • 它不会让我做 Collections.shuffle(queue) Collections 类型中的方法 shuffle(List>) 不适用于参数 (Queue)
  • 不需要使用队列,使用ArrayList 并在每次最后一个元素时删除,例如list.remove(list.size() - 1)
  • 即使洗牌成功了,优先级队列也会按照 1-75 的顺序给出整数。
  • @Flavio 我使用的是 ArrayList,我只是不知道如何处理丢失最后一个元素。如果我是正确的,那条线不会删除刚刚使用的数字......
  • @HassaanHafeez 是我的错,我没有仔细查看 Collections.shuffle,我已经用列表实现更新了答案。
【解决方案2】:

找到要删除的元素的索引:

int indexToRemove = list.indexOf(numberToRemove);

然后删除列表中该索引处的对象

list.remove(indexToRemove); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多