The program has a class relationship in which WeightedDie extends the Die class as follows:
import java.util.Random;
public class Die
{
private int _maxNumSides;
private Random _rand;
// class level variable with visibility for sub classes
protected int _faceValue;
public final static int DEFAULT_SIDES = 6;
// no param constructor for normal 6 sided die
public Die()
{
_rand = new Random();
_maxNumSides = DEFAULT_SIDES;
this.roll();
}
// will randomly reset the number of dots showing on a side
public int roll()
{
_faceValue = _rand.nextInt(_maxNumSides) + 1;
return _faceValue;
}
...
}
and
public class WeightedDie extends Die
{
private int randomNum;
private int maxNumSides = 6;
private double [] weights;
private Random rand;
private double sum = 0;
private double weightRoll;
private int cumulWeight;
private double cumulWeightDouble;
public WeightedDie()
{
super();
}
public WeightedDie(double[] w)
{
...
}
public int roll()
{
cumulWeight = 0;
cumulWeightDouble = 0;
weightRoll = 0;
rand = new Random();
randomNum = rand.nextInt(100) + 1;
for(int i = 0; i < 6; i++)
{
weightRoll = weights[i]*100;
cumulWeightDouble = weightRoll + cumulWeightDouble;
cumulWeight = (int) cumulWeightDouble;
if(randomNum >= (cumulWeight - weightRoll) && randomNum <= (cumulWeight))
{
_faceValue = i;
break;
}
}
return _faceValue;
}
}
My problem seems to be that the WeightedDie constructor uses the Die constructor with super(). In the Die constructor this.roll() is called, and this is calling WeightedDie's roll() instead of Die's roll(), which gives a null pointer. I want this.roll() in Die to call Die's roll() method. How can this be fixed?
答案 0 :(得分:-1)
在Die构造函数中调用this.roll(),这是调用WeightedDie的roll()而不是Die的roll(),
这是正确但不是问题。
给出一个空指针。
显示堆栈跟踪。可能这行有问题:
weightRoll = weights[i]*100;
因为weights
数组未初始化。
答案 1 :(得分:-1)
我们有以下选项来解决此问题。