-3

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

   }      
  • 1
    Where are you getting this `NullPointerException`? Highlight the specific line it occurs on. – Makoto Mar 09 '15 at 23:37
  • 1
    Where *exactly* do you get a null pointer exception? – Eric J. Mar 09 '15 at 23:38
  • maybe you should try to limit your code to the relevant parts for your question – ArchiFloyd Mar 09 '15 at 23:38
  • 1
    [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – MadProgrammer Mar 09 '15 at 23:51
  • The only reason I can think of for getting NPE where you indeicate (a stack trace would be nice) would be cause you're shadowing your variables – MadProgrammer Mar 09 '15 at 23:56
  • Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Mar 09 '15 at 23:57
  • 1
    Is that your exact code? It should be impossible to get an NPE on that line. – user253751 Mar 10 '15 at 00:00

1 Answers1

0

NullPointerException is caused when a variable is referenced when it hasn't been initialized (null). When this happens you should see a stack trace telling you what line number it happened on. Most typically the variable that was left null will appear on that line followed by a dot (followed by a method name). This dot demands that the variable not be null and will cause the NullPointerException.

The fix is to test for null if (x != null) ... before trying to use the variable or otherwise make sure this code is never encountered when x is null

x being whatever you left null.

candied_orange
  • 7,036
  • 2
  • 28
  • 62
  • The problem I am having is that my Car object takes 2 parameter (speed and name) I create an array of cars in a different class. I need to access the speed of those cars and pass them to a different variable. So right now, when I create an object of car (in my main class for example) it requires me to pass two parameters and those end up being what my getSpeed() refers to. Do you know how to access the speeds of the cars created in the array? – user_123945839432 Mar 09 '15 at 23:51
  • That's much different than a NullPointerException problem. Please update your question. – candied_orange Mar 09 '15 at 23:59
  • @HenriqueAguiar You do realise that people have been pouring over this code trying to find your issue, but you've not provided the actual code you've been using that generates your error?! Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Mar 10 '15 at 00:09
  • Thanks you MadProgrammer. I'll post the whole code. I had it all up until someone suggested asked to only put what was relative to my question. I must have missed something while editing. I'll change that. – user_123945839432 Mar 10 '15 at 00:16
  • @HenriqueAguiar what MadProgrammer said. Also, while I appreciate that you're still here and editing you're question is still worded so that NullPointerExceptions are your main concern. Please take some time and consider what you really want to ask. It might be time to just start a new question. – candied_orange Mar 10 '15 at 00:16
  • @HenriqueAguiar NO! MadProgrammer is asking you to post LESS. See http://stackoverflow.com/help/mcve – candied_orange Mar 10 '15 at 00:17