Can someone offer some insight on why the code doesnt work?
[edit: fixed code and new error]
I’m getting an error Exception in thread “main” java.lang.NullPointerException
and an error at the World.addCountry() (at line 8) code and an error at the addWorldplaces() (at line 5) code according to my output.
I have a feeling it’s something to do with not instantiating the world class? could it be possible?
public class World{
private Country[] countries;
private int numCountries=0;
public boolean addCountry(Country newCountry){
if(!(newCountry==null)){
countries[numCountries]=newCountry;
numCountries++;
return true;
}
else
return false;
}
}
public static void addWorldplaces(World pWorld){
Country usa=new Country("USA", 1);
pWorld.addCountry(usa);
}
Arrays are actually objects in Java. You need to allocate your
Countriesarray before you can use it. You’d typically do this in a constructor:You need to size your array appropriately. Alternatively, you could look at an
ArrayList, which will automatically grow in size if needed.