改组方法不能按预期工作

时间:2016-09-04 06:53:52

标签: java arrays constructor swap

在我的一堂课中,我写了这些专栏:

String[] score = {"2","3","4","5"};
player = new otherClass(score);
host = new otherClasee(score);
player.shuffle();
host.shuffle()

System.out.println("player is: " + Arrays.toString(player.point));
System.out.println("host is: " + Arrays.toString(host.point));

另一个类是:

public class otherClass {
   String[] point;
   public otherClass(String[] something){
      point = something;
   }
   public void shuffle(){
       int ind;
       String change;
       Random rand = new Random();
       for (int i = point.length - 1; i > 0; i--){
            ind = rand.nextInt(i+1);
            if (ind != i){
            change = point[i];
            point[i] = point[ind];
            point[ind] = swap;

  }
}

" shuffle()"是类内的方法" otherClass"交换点[]的元素。但我收到的结果是"播放器"和"主持人"以完全相同的方式洗牌。具体来说,"播放器"先洗牌,然后"主持人"是晚些时候。我期待两次洗牌是不同的。

2 个答案:

答案 0 :(得分:0)

您将相同的数组传递给两个构造函数,然后将其混洗,因此它当然具有与自身相同的值。如果您希望类实例具有独立副本,请为它们提供独立副本。

答案 1 :(得分:0)

您在对象“播放器”和“主机”中使用相同的String[]对象。 即使它们属于不同的类,您也可以给它们相同的对象实例“得分”。

解决方案是复制“得分”数组。

尝试

System.arraycopy(...)

您可以在构造函数或调用类中执行此操作。