1

我有一个 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);
4

2 回答 2

4

我会使用 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();
      }
    });
  }
}
于 2013-10-22T20:47:55.830 回答
0

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

int indexToRemove = list.indexOf(numberToRemove);

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

list.remove(indexToRemove); 
于 2013-10-22T20:46:41.150 回答