数组对象所有索引都具有相同的值java

时间:2014-12-25 14:37:42

标签: java arrays multidimensional-array

我有一个错误,我的数组返回所有相同的值,而我使用我在类中创建的print方法。我不知道为什么,它必须是不同的价值。有什么建议吗? 这是代码

主要课程:

public class KmeanES {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Kmean coba= new Kmean();

        coba.filldata();
        coba.print()
    }
}

Kmean班:

public class Kmean {

double[][] datadummy = {{15.26, 14.84, 0.871}, {5.763, 3.312, 2.221},
    {14.88, 14.57, 0.881}, {5.554, 3.333, 1.018}, {4.956, 114.29, 14.09},
    {0.905, 5.291, 3.337}, {2.699, 4.825, 1}, {13.84, 13.94, 0.8955},
    {5.324, 3.379, 2.259}, {4.805, 1, 16.14}, {14.99, 0.9034, 5.658}};
//11 dummy data
Kmeandata data = new Kmeandata();
Kmeandata[] datafinal = new Kmeandata[11];


void filldata() {


    double[] temp = new double[3];
    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 3; j++) {
            temp[j] = this.datadummy[i][j];

        }
        this.data.setData(temp);
        this.datafinal[i]=this.data;
        datafinal[i].printdata();

    }
}

void print() {
    for (int i = 0; i < 11; i++) {
        this.datafinal[i].printdata();

    }
}

}

和Kmeandata班

public class Kmeandata {

String kelas;
public double[] data = new double[3];

public Kmeandata(String kelas, double[] data) {
    this.setKelas(kelas);
    this.setData(data);
}

public Kmeandata(double[] data) {
    this.setKelas(null);
    this.setData(data);
}

public Kmeandata() {
    this.setKelas(null);
    this.setData(null);
}

public String getKelas() {
    return kelas;
}

public void setKelas(String kelas) {
    this.kelas = kelas;
}

public double[] getData() {
    return data;
}

public void setData(double[] data) {
    this.data = data;
}

public void printdata() {
    double[] temp = new double[3];

    temp = this.getData();
    System.out.println("");
    for (int i = 0; i < 3; i++) {

        System.out.printf("|" + temp[i] + "|");
    }
}

}

1 个答案:

答案 0 :(得分:1)

您传入的是对临时数组的引用,而不是副本。在外部for循环中移动temp的定义。

for (int i = 0; i < 11; i++) { 
  double[] temp = new double[3];
  for (int j = 0; j < 3; j++) { 
    temp[j] = this.datadummy[i][j];
  }
  ...
}