当尝试将我的Earthquake对象添加到我的数组列表中时,当前收到错误“java.lang.NullPointerException:null”。
注意:我正在使用BlueJ手动创建和输入我的地震的值。
这是我的地震课:
public class Earthquake {
// instance variables - replace the example below with your own
private double latitude;
private double longitude;
private double magnitude;
private int year;
public Earthquake(double latitude, double longitude, double magnitude, int year)
{
// initialise instance variables
this.longitude = longitude;
this.latitude = latitude;
this.magnitude = magnitude;
this.year = year;
}
public void storeLat (double longValue)
{
longitude = longValue;
}
public void storeLang (double latValue)
{
latitude = latValue;
}
public void storeMag (double magValue)
{
magnitude = magValue;
}
public void storeYear (int yearValue)
{
year = yearValue;
}
public int getYear ()
{
return year;
}
public double getMag ()
{
return magnitude;
}
public double getLat ()
{
return latitude;
}
public double getLong ()
{
return longitude;
}
}
这是我的Observatory类,用于创建数组列表并添加Earthquake对象:
import java.util.ArrayList;
public class Obersvatory {
private String ObsName;
private String ObsCountry;
private int ObsStartYear;
private double ObsLocation;
private ArrayList<Earthquake> quakes;
public Obersvatory()
{
this.ObsName = ObsName;
this.ObsCountry = ObsCountry;
this.ObsStartYear = ObsStartYear;
this.ObsLocation = ObsLocation;
ArrayList<Earthquake> quakes = new ArrayList<Earthquake>();
}
public void addQuakes(Earthquake e)
{
quakes.add(e);
}
}
我会对任何修复/提示表示感谢:)
答案 0 :(得分:3)
这样做
ArrayList<Earthquake> quakes = new ArrayList<Earthquake>();
您正在创建本地数组列表,其范围仅限于Obersvatory()
函数,因此只需使用它来初始化全局private ArrayList<Earthquake> quakes;
类列表
quakes = new ArrayList<Earthquake>();
答案 1 :(得分:2)
在Observatory
课程中,您有两个名称相同的变量quakes
。全局的永远不会被初始化(它是null
)。
您可以通过替换
来解决这个问题ArrayList<Earthquake> quakes = new ArrayList<Earthquake>();
使用:
quakes = new ArrayList<Earthquake>();
不要定义一个新变量,将全局变量初始化。