2011-04-11 47 views
0

这是一个名为placeShips()的方法,我通过另一种方法(由ButtonListener调用)调用。但是当所有被调用的时候,我会在最深的嵌套行 - System.out.println(ships [i]);上得到一个NullPointerException。该数组已在构造函数中的此代码之上进行声明和初始化。它被设置为等于一个等于3的常量整数。我在该打印输出中放置了一个简单的字符串,它可以工作。但是,无论何时该阵列卷入,它都变得混乱。出了什么问题?Do-While Loop中使用Array []的问题

NUM_SHIPS,NC_EMPTY,NC_SHIP,以及所有的标签/按钮都已经制作好了。

private Ships ships[]; 

*-----Constructor begins here-----* 
Ships[] ships = new Ships[NUM_SHIPS]; 
*-----Constructor ends here-----* 

ships[0] = new Ships("Aircraft Carrier", 5, false); 
ships[1] = new Ships("Battleship", 4, false); 
ships[2] = new Ships("Cruiser", 3, false); 

public void placeShips() 
{ 
    statusLabel.setText("Press [Play]"); 
    int shipsPlaced = 0; 

    do 
    { 
     int randomRow = (int)(Math.random()*ROWS); 
     int randomCol = (int)(Math.random()*COLS); 

     if (gameBoard[randomRow][randomCol] == NC_EMPTY) 
     { 
      gameBoard[randomRow][randomCol] = NC_SHIP; 
      shipsPlaced = shipsPlaced + 1; 

      for (int i = 0; i < NUM_SHIPS; i++) 
      { 
       System.out.println(ships[i]); 
      } 
     } 
    }while (shipsPlaced < NUM_SHIPS); 
} 
+0

是NUM_SHIPS等于ships.length? – 2011-04-11 01:21:44

+0

是placeShips()和ships []数组,是同一个类的成员?您是否曾尝试在println语句中放置断点并查看船舶数组是否已装运对象或数组是否为空? – brainydexter 2011-04-11 01:22:37

+0

您有称为“船”的类级别的数组变量吗?您在尝试在PlaceShips()中使用它之前确定要分配它吗?此外,它更好地构造for for循环为'for(int i = 0; i Dan 2011-04-11 01:22:43

回答

2

你有一个类级别数组变量:private Ships ships[];,但你在你的构造函数Ships[] ships = new Ships[NUM_SHIPS];定义。你有没有分配到类级变量?你可以尝试

/* Class Level */ 
private Ships _ships[]; 

/* In constructor */ 
_ships = new Ships[NUM_SHIPS]; 

/* In PlaceShips() */ 
for (int i = 0; i < _ships.Length; i++) 
{ 
    if(_ships[i] != null) 
    { 
     System.out.println(_ships[i].toString()); 
    } 
} 

如果不工作,那么调试代码以找到对象实际上是抛出异常

+0

+1首先识别此常见错误。 – camickr 2011-04-11 01:47:42

+0

谢谢。这有帮助。 – Joe 2011-04-11 01:49:11

0

它看起来像你的构造函数只初始化一个本地指定船舶的变量。你说你有:

-----Constructor begins here-----* 
Ships[] ships = new Ships[NUM_SHIPS]; 
*-----Constructor ends here-----*` 

但好像你真的想

ships = new Ships[NUM_SHIPS];

+0

这也有帮助,事实证明,我并不需要开始的船舶[]。它不再吐出错误!感谢大家。 – Joe 2011-04-11 01:50:08