我正在制作一个使用ansi代码创建战舰游戏的程序。 ansi代码没有太大问题,因为我发现这些代码允许我覆盖打印行。我的计划是使用它将船放在已经绘制的板上。我的问题在于放置船只的数组(“0”)。似乎无法通过nullpointerexception错误。我觉得这是阻止我完成程序的唯一因素。任何帮助都将受到高度赞赏。
我的计划的一部分在下面。
协调班级:
public class Coordinate {
public String piece;
int row, col, type;
public boolean select, empty, hit, ship;
public String [][] shipPiece;
public String section()
{
piece = "i";
empty = true;
select = false;
hit = false;
//ship = false;
if (empty)
{
piece = "\033[33m0\033[0m";
}
else if(!empty)
{
//empty = true;
ship = true;
piece = "0";
}
else if(!hit && ship)
piece = "\033[33m0\033[0m";
return piece;
}
public String placeShip()
{
for(int x = 0; x<=10; x++)
{
for(int y = 0; y<=10; y++)
{
shipPiece[x][y] = piece;
}
}
return piece;
}
}
玩家类:
public class Player {
private String name1, name2;
//private ArrayList<Coordinate> moves;
//private Coordinate move;
private int playerNumber;
Scanner in = new Scanner(System.in);
Board bawd = new Board();
Coordinate c = new Coordinate();
Ship sh = new Ship();
public Player(){}
public void GetNames()
{
for(playerNumber = 1; playerNumber <= 2; playerNumber++)
{
System.out.print("Player " + playerNumber + ": ");
name1 = in.nextLine();
playerNumber++;
System.out.print("Player " + playerNumber + ": ");
name2 = in.nextLine();
System.out.print("\033[2J");
}
}
public void setShips()
{
bawd.singleP1View();
sh.coordLoc();
System.out.println("\033[2J");
bawd.singleP2View();
sh.coordLoc();
System.out.println("\033[2J");
game();
}
public void game()
{
bawd.p1turn();
c.placeShip();
}
}
答案 0 :(得分:2)
shipPiece array
未初始化。
更改
public String [][] shipPiece;
到
public String [][] shipPiece = new String [11][11];
答案 1 :(得分:0)
这从未初始化
public String [][] shipPiece;
你应该初始化像这样的东西
public String [][] shipPiece = new String[10][10];
答案 2 :(得分:0)
您永远不会初始化shipPiece
。你必须以这种方式初始化它:
public String [][] shipPiece = new String[11][11];
答案 3 :(得分:0)
public String [][] shipPiece;
你没有初始化这个坏孩子!!!