我很困惑,为什么这个数组(cumulativeWeights)被认为是null。这是我(简化)代码:为什么数组在初始化时为空?
public class WeightedDieTester
{
public static void main(String[] args)
{
WeightedDie d = new WeightedDie();
}
}
public class Die
{
public Die()
{
this.roll();
}
}
public class WeightedDie extends Die {
double[] cumulativeWeights = {.1, .2, .3, .4, .5, 1};
public WeightedDie() {
}
public int roll() {
for (int i = 0; i < cumulativeWeights.length; i++) { //this is where the nullpointerException is occuring
if (randNum < cumulativeWeights[i]) {
return i + 1;
}
}
return 6;
}
}
所以呀,cumulativeWeights已经初始化,并不能为空。有谁知道为什么我得到这个nullpointerexception?
因为在'cumulativeWeights'已经被分配之前你在'Die'构造函数中调用'roll()'。 –
这甚至不应该编译。 – chrylis
'死'是抽象类吗? –