I'm trying to write a piece of code that can allow people to add data about different earthquakes in to different observatories, and allow you to pull data about them.
When I run through the terminal I can add observatories, but when it comes to adding an earthquake and putting them in to specific observatories I get a java.lang.Nullpointerexception error.
public void AddQuake(String name, int magnitude, int latitude, int longitude, int year) {
Observatory myObservatory = getObservatory(name);
// specify an observatory to store it in every time a quake is created.
Earthquake currentQuake = (new Earthquake(name, magnitude, latitude, longitude, year)); //setting local variable
allQuakes.add(currentQuake); //adding to arraylist
if (currentQuake.GetMagnitude() > 4) {
bigQuakes.add(currentQuake);
}
if (currentQuake.GetMagnitude() >= biggestMagnitudeEver) {
biggestQuakeEver = currentQuake; // decides the biggest earthquake ever recorded.
}
myObservatory.addQuakeHere(currentQuake); //adding to specified observatory
}
the getObservatory method is an iterator that selects observatories from an array list of observatory objects, it works fine everywhere else.
this all works fine until the last line. addQuakeHere is a method pulled from the observatory class to add and hold earthquakes in an arraylist, but when I run it through the terminal and get to this part I get a Java.lang.nullpointerexception message. Why?
as requested, the code for the observatory class:
public class Observatory
{
private ArrayList <Earthquake> quakes;
public Observatory(String name, String country, int startYear, int area) {
quakes = new ArrayList<Earthquake>(); //array list containing quakes.
//other constructors and things omitted.
}
public void addQuakeHere(Earthquake quake){
quakes.add(quake);
}
}
as requested, the getObservatory method:
public Observatory getObservatory(String name){ // method to select a certain observatory.
Iterator iter = allObservatories.iterator();
while(iter.hasNext()) { //while there is another observatory in the queue.
Observatory currentObserve =(Observatory) iter.next(); //move on to the next one.
if(name == currentObserve.GetName()){
return currentObserve; //if the name matches the input parameter, return the observatory.
}
}
return null;
}