1

This code is supposed to perform a "perfect shuffle" on a deck of cards. It represents the division of a deck into two decks and then the subsequent interleaving of them.
When I pass in an array and then print out the elements in the returned array, the elements are evidently shuffled. However, as the array in the perfectShuffle method is an alias of whatever array I pass into it, the original array back in the main method should also be "shuffled".
However, when I print out the array after performing the perfect shuffle method on it, the elements are not shuffled. When I check the same returned array, it is shuffled... I'm not sure why it isn't working. Could someone explain this to me?

public class Shuffler {

private static final int SHUFFLE_COUNT = 1;

private static final int VALUE_COUNT = 9;

public static void main(String[] args) {
System.out.println("Results of " + SHUFFLE_COUNT +
                         " consecutive perfect shuffles:");
  int[] values1 = new int[VALUE_COUNT];

  for (int i = 0; i < values1.length; i++) {
     values1[i] = i;
  }
  perfectShuffle(values1);

  for (int j = 1; j <= SHUFFLE_COUNT; j++) {
     System.out.print("  " + j + ":");
     for (int k = 0; k < values1.length; k++) {
        System.out.print(" " + values1[k]);
     }
     System.out.println();
  }
  System.out.println();
  }


  public static int[] perfectShuffle(int[] values) {
  int[] shuffle = new int[values.length];

  int k=0;

  for(int j=0; j<(values.length+1)/2; j++)
  {
     shuffle[k]=values[j]; 
     k+=2;  
  }

  k=1;
  for(int j=(values.length+1)/2; j<values.length; j++)
  {
     shuffle[k]=values[j];
     k+=2; 
  }
  values=shuffle;
  return values;

}
}
4

1 回答 1

1

这与通过引用和值传递的参数有关。您的代码有点混乱,并不清楚一下子看出问题所在。您按值传递数组。因此,指针 go 对象被复制。如果您处理了这个确切对象的项目,这可能会起作用。但是您在 perfectShuffle() 中创建了一个副本,并且 resulf 是对新对象的引用。但是,您永远不会在 main() 的代码中使用返回值

编辑:对评论的回答不适合评论大小。一些解释:阅读一些关于对象引用的信息。简而言之,对象 - 数组 - 占用连续的内存块,而对象引用是标准大小的变量,其中包含指向对象内存开始的指针。可能有很多引用指向同一个对象。当您调用函数并传递对象引用时,它会被复制。现在有 2 个引用,一个在主代码中,一个在子函数中。如果您修改函数内部的数组,就像arr[i] = value它实际上会修改对象一样,主引用会“看到”修改后的对象,因为只有一个对象。但是当你在函数中覆盖引用指向数组时,它只在函数内部有效,因为它是本地范围的副本,不会返回

于 2015-03-02T15:30:56.547 回答