访问类数据

时间:2014-10-10 18:59:57

标签: java

我正在尝试访问我使用结构创建的数据,但我似乎无法弄清楚如何。在我的课上我有3个变量。

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

我还有一个构造函数,可以创建此类的7个实例

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

我想知道如何为特定的类实例访问特定的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());
    }

2 个答案:

答案 0 :(得分:0)

为Data创建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);

答案 1 :(得分: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;
}    
     

}

并且在课堂外,例如在Main方法中创建对象:

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() );

}