1

我的目标是让用户输入一个数字 N,arrayList 的大小为 2N + 1。

最终,我的 N=2 的 arrayList 应该是“OO XX”。

public Board(int size)
    {
        tiles = new ArrayList<Tile>(size);

        for(int index = 0; index < size; index++)
        {
            tiles.add(new Tile('O')); 
            tiles.add(new Tile(' '));
            tiles.add(new Tile('X')); 

            System.out.print(tiles.get(index));
        }          

    }

上面的代码给了我“O XO”。如何修改它以显示 OO XX ?

提前谢谢!

4

4 回答 4

4

如果您想在一个循环中执行此操作,您可以这样做:

for (int i = 0 ; i != 2*size+1 ; i++) {
    tiles.add(new Tile(i==size ? ' ' : (i<size ? 'O' : 'X')));
}

这个想法是计算总大小(即2*size+1),然后使用条件来决定我们在中点的哪一侧。

于 2013-09-25T19:29:27.757 回答
2

您在单参数ArrayList(int)构造函数中传递的参数不是列表的固定大小。这只是初始容量。如果你的大小是固定的,那么你可以使用一个数组:

Tile[] tiles = new Tile[2 * n + 1];

Arrays#fill(Object[] a, int fromIndex, int toIndex, Object val)然后通过使用方法填充数组非常简单:

Arrays.fill(tiles, 0, n, new Tile('O'));
tiles[n] = new Tile(' ');
Arrays.fill(tiles, (n + 1), (2 * n + 1), new Tile('X'));

尽管如注释中所述,这将参考同一对象填充数组索引。可能适用于 immutable Tile,但不适用于 mutable 。

于 2013-09-25T19:31:33.340 回答
1

您的初始化tiles很好,但是其余的逻辑需要一些工作。

for(int index = 0; index < size; index++) {
  tiles.add(new Tile('O')); 
}
tiles.add(new Tile(' ')); 
for (int index = 0; index < size; index++) {
  tiles.add(new Tile('X'));
}

或者,如果你觉得自己很可爱……

tiles.addAll(Collections.nCopies(size, new Tile('O')));
tiles.add(new Tile(' '));
tiles.addAll(Collections.nCopies(size, new Tile('X')));

...尽管如果您希望Tile稍后修改对象,该版本可能会出现问题。

于 2013-09-25T19:25:42.467 回答
1

尝试这个:

// it's not necessary to specify the initial capacity,
// but this is the correct way to do it for this problem
tiles = new ArrayList<Tile>(2*size + 1);

// first add all the 'O'
for (int index = 0; index < size; index++)
    tiles.add(new Tile('O'));
// add the ' '
tiles.add(new Tile(' '));
// finally add all the 'X'
for (int index = 0; index < size; index++)
    tiles.add(new Tile('X'));

// verify the result, for size=2
System.out.println(tiles);
=> [O, O,  , X, X]
于 2013-09-25T19:26:36.317 回答