【问题标题】:Add Index of 2-dimensional Array to to the end of List in Java在Java中将二维数组的索引添加到列表的末尾
【发布时间】:2019-09-24 19:12:22
【问题描述】:

我正在开发一个小游戏,玩家单击一个按钮,其值来自二维数组。This is how the game looks 如果玩家想要恢复他的操作,我想将玩家采取的步骤保存在列表中,并且当他单击“还原”按钮时,列表的最后一项将被还原。问题是我不知道如何将二维数组的索引保存到列表中。

我的代码很远,因为数组在后面

for (int i = 0; i < buttons.length; i++) {
        for (int j = 0; j < buttons[i].length; j++) {
            counter++;
            buttons[i][j] = new JButton("" + counter);

            buttons[i][j].setBackground(Color.white);
            buttons[i][j].addActionListener(new ButtonPress());
            fenster.add(buttons[i][j]);

ActionListener 的代码在这里:

public void actionPerformed(ActionEvent e) {

        amountMoves++;
        moves.setText("Moves: " + amountMoves);

        int x = 0;
        int y = 0;
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                if (((JButton) e.getSource()).equals(buttons[i][j])) {
                    x = i; 
                    y = j;
                    break;
                }
            }
        }
    }

到目前为止,列表不是我的强项,我只有这个:

    ArrayList<Integer> steps = new ArrayList<Integer>();

我知道我可以使用steps.add() 添加一个元素并使用steps.remove(steps.size() - 1); 删除最后一个元素,但仅此而已

非常感谢任何帮助

编辑:在@Johnny Mopp 和@SSP 的帮助下,我想出了该怎么做。首先,我创建了一个 String 类型的 List ArrayList&lt;String&gt; steps = new ArrayList&lt;String&gt;();(您可以交替使用 JButton 类型的 List)并将其添加到带有 steps.add(buttons[i][j].getText()); 的 Actionlister 中

【问题讨论】:

  • 还原,是指 List 中的最后一项被删除,还是与前一项相同?
  • 我的意思是列表的最后一项被删除了
  • 有很多选择。您可能会存储实际的按钮 (ArrayList&lt;Button&gt;)?或者使用Pair.....的数组
  • 这对我有帮助,我想通了,非常感谢

标签: java arrays list add


【解决方案1】:

创建一个列表列表:-

ArrayList<ArrayList<Integer>> steps = new ArrayList<>();

如果您要保存第 2 行和第 2 列数据,保存值如下:-

steps.get(1).add(1{index of column},2{value to be stored});

如果你是第一次添加元素,你需要像下面这样实例化对象:-

if(steps.get(1) == null){
    steps.get(1) = new ArrayList<>();
}

访问数据

 steps.get(1).get(2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2021-01-26
    • 2021-04-21
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多