So I am trying to set the speed of an image that will move across the screen to a value set in a different class. In other words, I have a car class that creates a car with a speed value (getters and setters methods are there). I also have an Environment class that creates an array of cars and and populates the array with cars and uses a random number to set the speed of those cars. I am trying to access that speed value of the cars in the array in a different class using the getSpeed() method. However I keep getting a nullpointer. What is wrong in this code? Thanks!
public class Environment {
private Car[] garage;
private String[] carNames = {"BRITISH MOTOR COMPANY", "FAST AND FURIOUS", "SCOOBY GANG", "SPEEDY CADDY"};
private String[] trackNames = {"Boston", "New York", "Philidelphia", "Washington D.C."};
private Random random;
private int randomSpeed;
/**
* Constructor
*/
public Environment(){
random = new Random();
populateGarage();
}
/**
* Create the cars to be put into Tracks
*/
public void populateGarage()
{
garage = new Car[4];
Car car;
for(int i= 0; i < garage.length; i++)
{
//Get a random number between 5 and 10 to use as the random speed of a car
randomSpeed = random.nextInt(10);
if(randomSpeed < 5){
randomSpeed = randomSpeed +5;
}
car = new Car(carNames[i], randomSpeed);
garage[i] = car;
System.out.println(car.getName() +" has speed "+ car.getSpeed());
}
System.out.println("\n");
}
Class with the getter
public class Car
{
private String name;
//speed in kilometers/hour
private int speed;
public Car(String n, int s)
{
name = n;
speed = s;
}
public int getSpeed()
{
return speed;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public void setSpeed(int s)
{
speed = s;
}
}//End of Car.java
Lastly this is the class where I call the getSpeed() but it does not work.
import java.awt.Color;
import java.awt.Graphics;
public class RaceDisplay extends JPanel implements ActionListener{
private Image img1,img2,img3,img4;
private int velX;
private int x;
private Timer tm;
private Car car = new Car("",0);
private Environment env;
public RaceDisplay(){
tm = new Timer(30,this);
x=0;
velX = car.getSpeed(); <------------null pointer points to this line as the error.
}
public void actionPerformed(ActionEvent e) {
Environment env = new Environment();
env.populateGarage();
x=x+velX;
repaint();
}
}//End of RaceDisplay.java
I get a nullpointer exception when I call it. I tried testing with a method that would just print the getSpeed() value in a different class - that return a value of 0.
public static void main(String[] args) {
Environment env = new Environment();
Car car = new car("",0);
env.populateGarage();
System.out.println(car.getSpeed());
}