Java用一个数组填充多个数组

标签 java arrays loops

我有一个数组,其中包含一副牌中的所有 52 张牌。

ImageIcon[] cards = {aceSpadesIcon, twoSpadesIcon, ... }

然后我打乱该数组

for(int i = 0; i < cards.length; i++)
{
    int r = (int)(Math.random()*(i+1));
    ImageIcon swap = cards[r];
    cards[r] = cards[i];
    cards[i] = swap;
} 

现在我创建四个新数组来填充卡片数组。

ImageIcon[] row1 = new ImageIcon[13];
ImageIcon[] row2 = new ImageIcon[13];
ImageIcon[] row3 = new ImageIcon[13];
ImageIcon[] row4 = new ImageIcon[13];

现在我用现在的随机卡片数组填充这些数组

int j = 0;  
            while(j < cards.length)
            {
                if(j <= 13)
                {
                    Arrays.fill(row1, cards[j]);
                    j++;
                }
                else if(j <= 26)
                {
                    Arrays.fill(row2, cards[j]);
                    j++;
                }
                else if(j <= 39)
                {
                    Arrays.fill(row3, cards[j]);
                    j++;
                }
                else
                {
                    Arrays.fill(row4, cards[j]);
                    j++;
                }
            }

然后我将其显示在 Swing 窗口中,但出现一些错误。我应该有 4 行,每行 13 张不同的随机卡,但我得到 4 行,每行 1 张随机卡显示 13 次。如何修复我的循环,以便它用不同的卡片填充数组?

enter image description here

最佳答案

使用 System.arraycopy 填充行:

public static void main(String[] args) {
    Integer[] allCards = new Integer[52];
    for (int i = 0; i < allCards.length; i++) {
        allCards[i]=i;
    }
    List<Integer> cardList = new ArrayList<Integer>(Arrays.asList(allCards));
    Collections.shuffle(cardList);
    Integer[] cards = cardList.toArray(allCards.clone());

    Integer[] row1 = new Integer[13];
    Integer[] row2 = new Integer[13];
    Integer[] row3 = new Integer[13];
    Integer[] row4 = new Integer[13];

    int index = 0;
    System.arraycopy(cards, index, row1, 0, 13);
    index+=13;
    System.arraycopy(cards, index, row2, 0, 13);
    index+=13;
    System.arraycopy(cards, index, row3, 0, 13);
    index+=13;
    System.arraycopy(cards, index, row4, 0, 13);

    System.out.println(Arrays.toString(cards));
    System.out.println(Arrays.toString(row1));
    System.out.println(Arrays.toString(row2));
    System.out.println(Arrays.toString(row3));
    System.out.println(Arrays.toString(row4));


}

关于Java用一个数组填充多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568434/

相关文章:

c++ - 遍历文件的每一行

java - 基本java代码错误

java - 将锯齿状二维数组中的元素组合成一个新的锯齿状二维数组(深度复制问题)

c# - 如何静态声明一个对象数组

java - 从文件读取时出现循环问题

javascript - 循环 jQuery ajax 并传递参数的正确方法

java - JPA EntityManager持久方法不将实体保存到数据库,但持久后实体有id

java - Play Framework 中 AJAX 调用的部分渲染

java - 是否有更简单的方法来移动数组中的对象以使它们相邻?

arrays - 查找包含另一个数组子集的数组而不使用 @> 与 postgreSQL