无法初始化Java对象的二维数组 [英] Can't initialize 2D array of objects in Java
本文介绍了无法初始化Java对象的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让一艘战舰游戏,为此我需要的广场,这是一个人可以挑选地点的二维数组。然而,当我运行我的程序,我得到一个空指针异常,当我尝试调用resetBoard()函数。
战舰类:
公共类战舰
{
私人广场[] []正方形;
私人布尔aircraftCarrierSunk;
私人布尔battleshipSunk;
私人布尔submarineSunk;
私人布尔patrolBoatSunk;
私人诠释boardSize;
公众诠释转; 公共战舰(INT X)
{
广场=新广场[X] [X]
//的for(int i = 0; I< boardSize;我++)//不知道我需要这个
// {
//为(INT J = 0; J< boardSize; J ++)
// {
//广场[I] [J] =新广场();
//}
//}
boardSize = X;
aircraftCarrierSunk = FALSE;
battleshipSunk = FALSE;
submarineSunk = FALSE;
patrolBoatSunk = FALSE;
} 公共无效resetBoard()
{
的for(int i = 0; I< boardSize;我++)
{
对于(INT J = 0; J< boardSize; J ++)
{
广场[I] [J] .setContents(0);
}
}
}
驱动:
公共静态无效的主要(字串[] args)
{
战舰游戏=新战舰(5); //在一个5×5板打 的System.out.println(号战列舰!);
的System.out.println(----------- \\ n); 对(INT gameNumber = 1; gameNumber&下; = 2; gameNumber ++)
{
game.resetBoard();
解决方案
得到它 - 在注释战舰
的线条,然后移动 boardSize = X;
上面的for循环
I'm trying to make a battleship game, for which I need a 2D array of squares, which are the places that a person can pick. When I run my program however, I get a null pointer exception when I try to call the resetBoard() function.
Battleship class:
public class Battleship
{
private Square[][] squares;
private boolean aircraftCarrierSunk;
private boolean battleshipSunk;
private boolean submarineSunk;
private boolean patrolBoatSunk;
private int boardSize;
public int turns;
public Battleship(int x)
{
squares = new Square[x][x];
// for(int i = 0; i < boardSize; i++) //not sure if I need this
// {
// for(int j = 0; j < boardSize; j++)
// {
// squares[i][j] = new Square();
// }
// }
boardSize = x;
aircraftCarrierSunk = false;
battleshipSunk = false;
submarineSunk = false;
patrolBoatSunk = false;
}
public void resetBoard()
{
for(int i = 0; i < boardSize; i++)
{
for(int j = 0; j < boardSize; j++)
{
squares[i][j].setContents(0);
}
}
}
Driver:
public static void main (String [] args)
{
Battleship game = new Battleship(5); // play on a 5 by 5 board
System.out.println("Battleship!");
System.out.println("-----------\n");
for (int gameNumber = 1; gameNumber <= 2; gameNumber++)
{
game.resetBoard();
解决方案
Got it- uncomment the lines in Battleship
, and then move boardSize = x;
above that for loop.
这篇关于无法初始化Java对象的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文