happyvirus
happyvirus

Reputation: 286

How to access object fields in a loop?

I can access the planetName, but not the Surfacematerial,Diameter etc because they are not in the array and in the object. How do I access the objects in a loop and their respective fields?

import java.util.Scanner; public class Planet {

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




        }
    }

Upvotes: 1

Views: 403

Answers (2)

Sage
Sage

Reputation: 15418

The staff array is declared as local in the Constructor: Or if it is declared in the class context, you are hiding it. So declare the staff array in the class context and then initialize in the constructor:

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

  }
}

And then, in the main function:

public static void main(String[] args) {
    Tester t = new Tester();

    t.staff[i].name = "A Name";
}

However, instead of accessing member field directly it is suggested to use getter or setter function like: getStaff(i) and similar.

Upvotes: 0

stinepike
stinepike

Reputation: 54722

just access like following

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

in your case say the first member name is name .. so call like

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

Upvotes: 2

Related Questions