package survival;
public class World {
private int width;
private int height;
private int distancePenalty = 2;
private int turnPenalty = 4;
private double hungerPenalty = 0.1;
private Plant[] plants;
private Herbivore[] herbivores;
private Carnivore[] carnivores;
private int[] newestHerbivore;
private int[] newestCarnivore;
public World(int plantNumber, int herbivoreNumber, int carnivoreNumber, int width, int height) {
this.width = width;
this.height = height;
plants = new Plant[plantNumber];
for (int i = 0; i < plantNumber; i++) {
plants[i] = new Plant(Math.random() * width, Math.random() * height);
}
herbivores = new Herbivore[herbivoreNumber];
for (int i = 0; i < herbivoreNumber; i++) {
herbivores[i] = new Herbivore(Math.random() * width, Math.random() * height);
//////////// This line causes java.lang.NullPointerException
newestHerbivore[i] = 1;
}
carnivores = new Carnivore[carnivoreNumber];
for (int i = 0; i < carnivoreNumber; i++) {
//////////// This line causes java.lang.NullPointerException
newestCarnivore[i] = 1;
}
}
}
Why is this line:
newestHerbivore[i] = 1;
an element causing an exception?
You need to initialize the array before you assign to it:
BTW: arrays are cumbersome and inflexible. In Java, you should use Collections instead. In most cases, ArrayLists will do fine as a replacement for array code.