0

I am trying to get the speed of a car object. Actually of all cars stored in an array and then pass that value to another variable.

So heres an example of what I have:

public class Car
{
    private int speed;

    public Car(int s)
    {
        speed = s;
    }

    public int getSpeed()
    {
        return speed;
    }
    public void setSpeed(int s)
    {
        speed = s;
    }
}

I have a class that creates an array of cars.

public class Environment {

private Car[] garage;   
private Random random;


public Environment(){
    random = new Random();
    populateGarage();
}

public void populateGarage()
{
    garage = new Car[4];
    int randomSpeed;
    Car car;

    for(int i= 0; i < garage.length; i++)
    {
        randomSpeed = random.nextInt(10);
        if(randomSpeed < 5){
            randomSpeed = randomSpeed +5;
        }
        car = new Car(carNames[i], randomSpeed);
        garage.add(car);

        System.out.println("car has speed "+ car.getSpeed());
    }

All works fine up to this point. Now I am trying to access that value in a different class. Here's an example:

public class RaceDisplay extends JPanel implements ActionListener{

   private int velX;
   private int x;
   private Car car;
   private Environment env;


public RaceDisplay(){

        x=0;
        velX=env.getArray[0]... (the velocity value should be one of the car's speeds) <-------------
    }

    public void paintComponent(Graphics g){

        super.paintComponent(g);
      //  (....)

    }
    public void actionPerformed(ActionEvent e) {

       x=x+velX;
           if(x>=650){
           x=0;
           x=x+velX; 
  }
}

I'm stuck on how to access that information through another class. Any help is most welcome.

1 Answer 1

1

because garage is a private field you will need a getter function set up in Environment

public Car getGarage (int index) {
    return garage [index];
}

Of course if you are not interested in the Car object at all and just want the speed you could write a method to that like:

public int getSpeedOfCar (int index) {
    return garage [index].getSpeed ();
}
Sign up to request clarification or add additional context in comments.

1 Comment

So a getter in the environment class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.