2014-12-25 99 views
1

我有一個錯誤,我的數組返回所有相同的值,而我使用的是我在類中創建的打印方法。我不知道爲什麼,它必須是不同的價值。任何建議? 這裏的代碼數組對象的所有索引都具有相同的值java

主要類:

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

您正在傳遞對temp數組的引用,而不是副本。將外部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]; 
    } 
    ... 
} 
相關問題