我需要创建一个程序,使用数组将一副牌重新排序。我应该将原来的 52 张牌切成两半,并通过交替放置任一堆牌中的牌将牌放入新的牌堆中。原始顺序 1,2,3,4....49,50,51,52 应按 1,27,2,28,3...26,52 的顺序出现。
public static void main(String[] args)
{
int[] array = new int[52];
int[] top = new int[26];
int[] bottom = new int[26];
for(int i=0; i < 52; i++)
{
array[i] = i+1;
}
for(int i = 0; i < 26; i++)
{
top[i] = array[i];
}
for(int i = 0; i < 26; i++)
{
bottom[i] = array[i+26];
}
System.out.println(shuffle(array, top, bottom));
}
public static int[] shuffle(int[] array, int[] top, int[] bottom)
{
for(int j = 0; j < top.length; j--)
{
array[j*2] = top[j];
array[j*2-1] = bottom[j];
}
return array;
}
我的问题是遇到越界异常。我不知道如何解决这个问题。即使我执行 array[j*2+1] 我仍然有这个问题。
最佳答案
for(int j = 0; j < top.length; j--)
从 0 开始,然后递减 j。所以第二次迭代将尝试访问索引-1。
事实上,即使是第一个也会,因为它尝试访问索引 j*2-1
,当 j 为 0 时,该索引为 -1。
关于Java使用数组完美shuffle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011599/