2014-10-10 74 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()); 

}