I am working on a program to create a battleship game using ansi codes. The ansi codes isn't much of a problem, since I found out that these codes allow me to overwrite print lines. My plan was to use this to place ships on a already drawn board. My problem lies in my array that's placing the ships ("0"). Can't seem to get past the nullpointerexception error. I feel that this is the only thing stopping me from finishing the program. Any help would be highly appreciated.
A portion of my program is below.
Coordinate Class :
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;
}
}
Player class :
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();
}
}
The shipPiece array
is not initialized.
Change
public String [][] shipPiece;
to
public String [][] shipPiece = new String [11][11];
This has never been initialized
public String [][] shipPiece;
You should initialize something like this
public String [][] shipPiece = new String[10][10];
You never initialize your shipPiece
. You have to initialize it for example this way:
public String [][] shipPiece = new String[11][11];
public String [][] shipPiece;
您没有初始化这个坏男孩!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.