So, I am a computer science student and a young Java programmer. Someone asked me to help them in a task where they need to create a fairly basic minesweeper program. This program does not use mines with a mark at all, but, in addition, it is functionally the same as any other sweeping game.
I am throwing a NullPointerException when I try to run a program. I researched what this could mean, and now I know that it really should be a NoObjectException or DereferenceException, but I'm still not closer to solving the problem.
This exception occurs when the makeField method of the Tile class is called. Also, I'm really trying to bow my head to the correct inheritance, static or non-static, public vs. private and how all these relationships are interconnected, so I'm sorry if this is a general noob question.
So, I have a main file, a class superclass and two subclasses of the tile class - Bomb and Flat. A bomb is a tile with a bomb in it, and Flat is any tile that is not a bomb.
public class MineSweeperMain{ public static void main(String[] args) { Scanner kybd = new Scanner(System.in); int dimension; Tile[][] gameBoard; System.out.print("Enter the dimension of the board you would like to play on:\t"); dimension = kybd.nextInt(); gameBoard = Tile.makeField(dimension); Tile.printField(gameBoard, dimension); } }
//
public class Tile { static Random rand = new Random(); boolean isBomb; boolean isRevealed; int posX, posY; int noOfAdjacentMines; public Tile() { isRevealed = false; } public static int detectMines(Tile[][] board, int dimensions) { int detectedMines = 0; for(int i = 0; i < dimensions; i++) { for(int j = 0; j < dimensions; j++) { if(board[i][j].isBomb) detectedMines++; } } return detectedMines; } public static Tile[][] makeField(int dimensions) { int rowOfMines = dimensions / 3; int randomInRow; Tile[][] Board = new Tile[dimensions][dimensions]; for(int i = 0; i < dimensions; i++) for(int j = 0; j <= rowOfMines; j++) { randomInRow = rand.nextInt(dimensions); Board[i][randomInRow] = new Bomb(); } for(int i = 0; i < dimensions; i++) for(int j = 0; j < dimensions; j++) { if(!Board[i][j].isBomb) Board[i][j] = new Flat(); } return Board; } public static void printField(Tile[][] board, int dimensions) { for(int i = 0; i <= dimensions; i++) { for (int j = 0; j <= dimensions; j++) { if(i ==0) System.out.print(i + " "); else if(j == 0) System.out.print(j + " "); else { if(board[i-1][j-1].isRevealed && !board[i-1][j-1].isBomb) System.out.print(board[i-1][j-1].noOfAdjacentMines + " "); else System.out.print("# "); } } } } }
//
public class Flat extends Tile{ public Flat() { noOfAdjacentMines = 0; isBomb = false; isRevealed = false; } }
//
public class Bomb extends Tile{ public Bomb() { isBomb = true; isRevealed = false; } }
//