问题
I need to create a program that uses arrays that shuffles a deck back into order. I am supposed to cut the original deck of 52 in half and place the cards in a new pile by alternately placing cards from either pile. The original order 1,2,3,4....49,50,51,52 should come out in the order 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;
}
My problem is that I am having an out of bounds exception. I am not sure how to fix this. Even if I do array[j*2+1] I still have this issue.
回答1:
change shuffle to:
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;
}
public static String print(int[] array)
{
String result="";
for(int j = 0; j < array.length; j++)
{
result=result+top[j];
}
return result;
}
call it like this:
System.out.println(print(shuffle(array, top, bottom)));
回答2:
for(int j = 0; j < top.length; j--)
You start from 0, and then decrement j. So the second iteration will try to access index -1.
And in fact, even the first one will, since it tries to access the index j*2-1
which is -1 when j is 0.
回答3:
On your first iteration when j=0 array[j*2-1] becomes array[-1] and results in exception. Anyways the whole logic is incorrect, there is no reason to decrement j
来源:https://stackoverflow.com/questions/20011599/java-perfect-shuffle-using-arrays