我正在编写一个程序来模仿“交易或不交易”游戏。上一掷千金获取NullPointerException与对象数组
背景:http://en.wikipedia.org/wiki/Deal_or_No_Deal
在工作到最终产品,我已经写了多个等级。然而,我试图测试我的一个类,并继续获得NullPointerException.
我写了一个名为Box的类,它创建了“box”对象。盒子对象是玩家选择的实际盒子。它由一个true/false值和一个double boxValue组成。 boolean variable
表示它是否打开/关闭(true表示打开,false表示关闭)。 double boxValue是分配给该框的实际值。
public class Box {
//instance fields
private double boxValue; // the amount of $ in each box
private boolean openClose; // whether or not the box is closed
//Constructor
public Box(double boxValue) {
this.openClose = false;
this.boxValue = boxValue;
if (boxValue < 0) {
throw new IllegalArgumentException("Box value must be greater than 0");
}
}
}
我已经写了另一个名为BoxList的类。这将创建一个Box对象数组,当它与我计划编写的其他类相结合时,它将作为游戏板。主要思想是BoxList中的构造函数通过使用传入的double array
作为参数来创建数组,然后创建一个与double数组传递的长度相同的Box对象数组,并为每个元素的double值赋值parameter array
,作为对应元素的Box对象array
的值。
我写了一个示例主要方法来测试,但是当我尝试获取BoxList数组中Box的特定element
的值时,我得到NullPointerException。任何人都可以提供建议来帮助解决这个问题。
(这是一个更大的计划的剪......我已经写了这么多,我不想再阻塞)
public class BoxList {
private Box[] boxArray;
public BoxList(double[] monetaryAmounts) {
Box[] boxArray = new Box[monetaryAmounts.length];
for (int i = 0; i < boxArray.length; i++) {
boxArray[i] = new Box(monetaryAmounts[i]);
}
}
public double getValue(int index) {
return boxArray[index].getValue();
}
// A sample main method to test out various object methods
public static void main(String[] args) {
double[] monetaryAmounts = {.5, 1, 3, 7.5, 8, 10}; // test array
BoxList test = new BoxList(monetaryAmounts);
System.out.println(test.getValue(0));
}
你什么行空指针异常?给我们留下评论。 –
当我在BoxList的末尾(用于getValue方法)超出println语句时获取它。返回boxArray [index] .getValue();' – Rivers31334