2014-10-10 72 views
0

我想訪問我使用結構創建的數據,但我似乎無法弄清楚如何。在我的課上,我有3個變量。訪問類數據

public class Data 
{ 
    private double tempCelc; 
    private double tempKelv; 
    private double tempFahr; 
} 

我也有創建此類

Data(final double tempCelcius) 
{ 
    this.tempCelc = tempCelcius; 
    this.tempFahr = this.celToFar(tempCelcius); 
    this.tempKelv = this.celToKel(tempCelcius); 
} 

的7個實例構造函數我不知道怎麼我能得到有關訪問的具體tempFahr或tempKelv爲類的特定實例。這是我的循環使用的構造:

for(int i = 0; i < temperatures.length; i++) 
    { 
     System.out.println("Please enter the temperature in Celcius for day " + (i+1)); 
     temperatures[i] = new Data(input.nextDouble()); 
    } 
+0

創建的getter/setter的類和訪問'tempFahr'一審使用'溫度[0] .getTempFahr()'。 – Braj 2014-10-10 19:01:32

回答

0

創建getter和setter方法對數據

public class Data 
{ 
    private double tempCelc; 
    private double tempKelv; 
    private double tempFahr; 

    Data(final double tempCelcius) 
    { 
     this.tempCelc = tempCelcius; 
     this.tempFahr = this.celToFar(tempCelcius); 
     this.tempKelv = this.celToKel(tempCelcius); 
    } 

    //getter example 
    public double getTempFahr() 
    { 
     return this.tempFahr; 
    } 
    //setter example 
    public void setTempFahr(double tempFahr) 
    { 
     this.tempFahr = tempFahr; 
    } 
    //add other getter and setters here 
} 

等等

訪問,如:

temperatures[0].getTempFahr(); 
temperatures[0].setTempFahr(80.5); 
+0

該setter將需要更新其他兩個領域,因爲他們的目的是等同的表示。我會完全避免使用setters,並使這些字段最終生成,這足以創建一個表示新溫度的新實例。 – 2014-10-10 20:09:13

+0

實際上,無論您何時更改,都不需要用新值調用所有3個setter。但是你也可以製造一個不變的物體。 – brso05 2014-10-10 20:10:48

0

你的模型班應該看起來像這樣:

public class Data{ 

private double tempCelc; 
private double tempKelv; 
private double tempFahr; 

// constructor method 
Data(final double tempCelcius) 
{ 
    this.tempCelc = tempCelcius; 
    this.tempFahr = this.celToFar(tempCelcius); 
    this.tempKelv = this.celToKel(tempCelcius); 
} 
// Accessor methods implementation 
public double getTempCelc(){ 
    return this.tempCelc; 
} 


public double getTempKelv(){ 
    return this.tempKelv; 
} 


public double getTempFahr(){ 
    return this.tempFahr; 
}  

}

進出類,例如的你的主要方法創建對象:

for(int i = 0; i < 10; i++) 
    { 
     System.out.println("Please enter the temperature in Celcius for day " + (i+1)); 
     temperatures[i] = new Data(input.nextDouble()); 
    } 

然後你訪問它們:

for(int i = 0; i < temperatures.length; i++){ 

    System.out.println("i : " + i + " cecl : " + temperatures[i].getCelc() + " kelvin : " + temperatures[i].getTempKelv() + " fahr : " + temperatures[i].getFahr()); 

}