我有一个数组,其中包含一副牌中的所有 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 次。如何修复我的循环,以便它用不同的卡片填充数组?
最佳答案
使用 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/