0

currently getting the error "java.lang.NullPointerException: null" when attempting to add my Earthquake objects into my array list.

Note: I am using BlueJ to manually create and input values for my Earthquake(s).

Here is my earthquake class:

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;
    }
}

And here is my Observatory class which is used to create the array list and add the Earthquake objects:

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

}

I'd be grateful on any fixes / tips :)

BackSlash
  • 21,927
  • 22
  • 96
  • 136
BlueBull
  • 75
  • 1
  • 1
  • 6

2 Answers2

3

by doing this

 ArrayList<Earthquake> quakes = new ArrayList<Earthquake>();

your are creating local array list who's scope is limited to Obersvatory() function so just use it like this to initialize the global private ArrayList<Earthquake> quakes; list of class

quakes = new ArrayList<Earthquake>();
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
2

In your Observatory class, you have 2 variables with the same name quakes. The global one is never initialized (it is null).

You can fix that by replacing

ArrayList<Earthquake> quakes = new ArrayList<Earthquake>();

with:

quakes = new ArrayList<Earthquake>();

Don't define a new variable, initalize the global one.

Titus
  • 22,031
  • 1
  • 23
  • 33