gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:12 25 4
gpt4 key购买 nike

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

主类:

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] + "|");
}
}

}

最佳答案

您正在传递对临时数组的引用,而不是副本。将 temp 的定义移到外部 for 循环内。

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];
}
...
}

关于java - java数组对象的所有索引都具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27648139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com