【问题标题】:How to access object fields in a loop?如何在循环中访问对象字段?
【发布时间】:2013-12-08 07:07:51
【问题描述】:

我可以访问行星名称,但不能访问 Surfacematerial、Diameter 等,因为它们不在数组和对象中。如何访问循环中的对象及其各自的字段?

导入 java.util.Scanner; 公共类星球{

    private String[] planetName;
    private String SurfaceMaterial;
    private double daysToOrbit;
    private double diameter;




public Planet(){


    planetName=new String[8];
    SurfaceMaterial="";
    daysToOrbit=0;
    diameter=0;





}


public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter){

    this.planetName=planetName;
    this.SurfaceMaterial=SurfaceMaterial;
    this.daysToOrbit=daysToOrbit;
    this.diameter=diameter;




}

public void setPlanetName(){

    Scanner in=new Scanner(System.in);

    Planet solar[]=new Planet[8];
    for(int i=0;i<solar.length;i++){


        solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter);
        System.out.println("Enter Planet Name::");
        planetName[i]=in.next();
        System.out.println("Enter Surface Material");
        SurfaceMaterial=in.next();
        System.out.println("Enter Days to Orbit");
        daysToOrbit=in.nextDouble();
        System.out.println("Enter Diameter");
        diameter=in.nextDouble();
    }

    for(int i=0;i<solar.length;i++){
    System.out.println(planetName[i]);
    System.out.println(this.SurfaceMaterial); //This returns only one value that has been entered at the last
    }


}









}   


    public static void main(String[] args) {

        Planet planet=new Planet();
        Scanner input=new Scanner(System.in);

    planet.setPlanetName();




        }
    }

【问题讨论】:

    标签: java arrays eclipse object constructor


    【解决方案1】:

    按照以下方式访问

    object[index].member ... // or call getter setter
    

    在您的情况下,说第一个成员名称是 name .. 所以像这样称呼

    staff[0].name // this will return BOB
    

    【讨论】:

    • for(int i=0;i
    • 这里的表面材料是什么......在问题中发布您的详细代码
    • 我认为他在声明人员数组时遇到了问题,因为他在构造函数中声明为本地
    【解决方案2】:

    staff 数组在构造函数中声明为本地:或者如果它在类上下文中声明,则隐藏它。所以在类上下文中声明staff数组,然后在构造函数中初始化:

    class Test
    {
      public Full_time [] Staff;
    
      public Test()
      {
    
        Staff = new Full_time [4];
    
        Staff [0] = new Full_time("BoB", 2000, 70000);
        Staff [1] = new Full_time("Joe", 1345, 50000);
        Staff [2] = new Full_time("Fan", 3000, 80000);
    
      }
    }
    

    然后,在主函数中:

    public static void main(String[] args) {
        Tester t = new Tester();
    
        t.staff[i].name = "A Name";
    }
    

    但是,建议不要直接访问成员字段,而是使用 getter 或 setter 函数,例如:getStaff(i) 和类似的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2015-06-07
      • 2013-07-07
      • 2012-02-29
      相关资源
      最近更新 更多