简体   繁体   English

ArrayList和Doubles

[英]ArrayList and Doubles

I have a BINGO game that has a button that acts as the caller. 我有一个BINGO游戏,有一个按钮作为调用者。 Each time I click the button I want a randomized number between 1-75. 每次我点击按钮,我想要一个1-75之间的随机数。 I have the following code to try and eliminate the duplicates but I have no idea on how to move on from here. 我有以下代码尝试消除重复,但我不知道如何从这里继续前进。 I basically need to remove the number from the ArrayList for the next time I click the button. 我基本上需要从下一次单击按钮时从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);

I would use a LinkedList instead of an Arraylist, populate it in the constructor and then let the LinkedList do all the work for you. 我会使用LinkedList而不是Arraylist,在构造函数中填充它,然后让LinkedList为您完成所有工作。 Something like: 就像是:

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();
      }
    });
  }
}

Find the index of element to be removed : 找到要删除的元素的索引:

int indexToRemove = list.indexOf(numberToRemove);

Then remove the object at that index in the list 然后删除列表中该索引处的对象

list.remove(indexToRemove); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM