[英]Java Exception when Adding Items to an Array
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;
}
}
}
為什么這行:
newestHerbivore[i] = 1;
導致異常的元素?
您需要先初始化數組,然后再分配給它:
herbivores = new Herbivore[herbivoreNumber];
newestHerbivore = new int[herbivoreNumber];
順便說一句:數組既麻煩又不靈活。 在Java中,您應該改用Collections。 在大多數情況下,ArrayLists可以很好地替代數組代碼。
您永遠不會初始化newestHerbivore
數組,因此嘗試分配給它的元素會觸發NPE。
newestCarnivore
。
我認為您的問題中的以下措辭可能可以解釋這種混淆: 為什么要添加元素...您沒有添加元素,而是要更改現有元素的值 。 在您的情況下,該元素不存在,因為數組引用為null
(本質上,整個數組不存在)。
這兩個數組的確切目的尚不清楚,因此我不願提出有關如何解決此問題的建議。 基於這兩個變量的名稱以及您的評論,我的猜測是它們實際上應該是標量變量而不是數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.