"거래 또는 거래 금지"게임을 모방하는 프로그램을 작성하고 있습니다. 거래 또는 거래 없음에개체 배열로 NullPointerException 받기
배경은 : http://en.wikipedia.org/wiki/Deal_or_No_Deal
최종 제품까지 작업에서 나는 다양한 클래스를 작성했습니다. 그러나, 나는 내 클래스 중 하나를 테스트, 나는 "상자"개체를 만듭니다 박스라는 클래스를 쓴 NullPointerException.
을 얻기 위해 계속 노력하고 있어요. 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 Object 배열을 만들고 해당 배열 요소의 double 값을 할당한다는 것입니다. parameter array
을 해당 요소로 Box 객체 array
의 값으로 설정합니다.
테스트 할 샘플 main 메서드를 작성했지만 BoxList 배열에있는 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));
}
에 어떤 라인이에 널 포인터 예외를받을 수 있나요? 의견을 남겨주세요. –
(getValue 메서드의 경우) BoxList의 끝에서 println 문을 실행하면됩니다. 'return boxArray [index] .getValue(); '에서 던져진 예외 – Rivers31334