创建对象数组并读取信息

时间:2015-05-23 10:44:19

标签: java arrays

我正在创建一个带有框对象的Box [](即box [box1,box2,box3]),然后编写一个方法来访问Box []中的元素,我没有遇到指针错误。

public class GameState
{
public static final int noOfSquares = 10; // the extent of the board in both directions
public static final int noOfBoxes   = 3;  // the number of boxes in the game 

private Square[][] board; // the current state of the board 
private Box[] boxes;      // the current state of the boxes 
private int score;        // the current score

// initialise the instance variables for board 
// all squares and all boxes are initially empty 
public GameState()
{
    score = 0;
    board = new Square[10][10];       
    Box[] boxes = new Box[3];
    for(int j =0;j<boxes.length;j++){
        boxes[j] = new Box();
     }

 // return the current state of the board 
public Square[][] getBoard()
{
    return board;
}

// return the current contents of Box i 
public Box getBox(int i)
{
    if (0 <= i && i < noOfBoxes)       **// here doesn't work**
    { 
        return boxes[i];
      }
    else         {
        return null;
}
}

// return the current score
public int getScore()
{
    return score;
}

  }

}

框类中没有错误,其中Box()创建一个新的空框。 感谢帮助。

1 个答案:

答案 0 :(得分:2)

shadowing变量boxes。取代

Box[] boxes = new Box[3];

boxes = new Box[3];