所以我试图将在屏幕上移动的图像的速度设置为在不同类中设置的值。换句话说,我有一个汽车类,可以创建一个具有速度值的汽车(getters和setters方法就在那里)。我还有一个环境类,它创建一个汽车数组,并用汽车填充数组,并使用随机数来设置这些汽车的速度。 我试图使用getSpeed()方法在不同的类中访问数组中汽车的速度值。但是我一直得到一个nullpointer。这段代码有什么问题?谢谢!
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");
}
带有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
最后,这是我调用getSpeed()的类,但它不起作用。
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
当我调用它时,我得到一个nullpointer异常。我尝试使用一种只在另一个类中打印getSpeed()值的方法进行测试 - 返回值为0.
public static void main(String[] args) {
Environment env = new Environment();
Car car = new car("",0);
env.populateGarage();
System.out.println(car.getSpeed());
}
答案 0 :(得分:0)
NullPointerException是在未初始化(null)时引用变量时引起的。当发生这种情况时,您应该看到堆栈跟踪,告诉您它发生了什么行号。最常见的是,保留为null的变量将出现在该行上,后跟一个点(后跟方法名称)。这个点要求变量不为null并且会导致NullPointerException。
修复是在尝试使用变量之前测试null if (x != null)
...或者确保在x为null
时永远不会遇到此代码
x是你留下的任何东西。