[英]Java fill multiple arrays with one array
我有一个包含甲板上所有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++;
}
}
然后我在一个秋千窗口显示它,但我有一些错误。 我应该有4行,每行有13个不同的随机卡,但我得到4行,每个行显示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));
}
检查javadoc for Arrays.fill
它将所有数组的元素设置为指定的值。 你需要的是row1 [j] = cards [j],依此类推。 顺便说一句,如果我是你,我会在循环设置row1 [j] = cards [j],row2 [j] = cards [j + 13]等中迭代13次,因为这更清楚地显示了你的意图。
来自Java SE 7文档:
fill
public static void fill(Object[] a,
Object val)
Assigns the specified Object reference to each element of the specified array of Objects.
Parameters:
a - the array to be filled
val - the value to be stored in all elements of the array
Throws:
ArrayStoreException - if the specified value is not of a runtime type that can be stored in the specified array
所以你正在做的是(反复地)用一个值填充每个数组。 你想要的将是更多的东西:
while(j < cards.length)
{
if(j < 13)
{
row1[j] = cards[j];
}
else if(j < 26)
{
row2[j%13] = cards[j];
}
else if(j < 39)
{
row3[j%13] = cards[j];
}
else
{
row4[j%13] = cards[j];
}
j++;
}
这仍然相当混乱(如果可能的话,避免使用硬编码的常量),但至少它会做你想要做的事情。 请注意,您的原始数组应该是0索引的,因此您的逻辑应该转换为1。 此外,尝试避免重复的代码(注意增量只发生一次,因为它通过循环的所有通过)。
不要使用Arrays.fill
,即用你给它的值填充整个数组。 尝试这样的事情:
for (int j = 0; j < cards.length; j++)
{
if(j < 13)
{
row1[j] = cards[j];
}
else if(j < 26)
{
row2[j - 13] = cards[j];
}
else if(j < 39)
{
row3[j - 26] = cards[j];
}
else
{
row4[j - 39] = cards[j];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.