Java编程新手求助:战舰游戏GameBoard类代码相关问题
Hey there! Let's break down your GameBoard class and fix those issues step by step, since you're working on your battleship assignment as a new Java developer.
First, let's address the immediate compile error in your code: your constructor names don't match the class name. Your class is GameBoard, but you've named your constructors Grid—that won't work in Java, since constructors must share the exact name of their class.
Here's the corrected and completed version of your GameBoard class, with clear explanations:
public class GameBoard { public int[][] values; // Default constructor: initializes a 10x10 grid (standard battleship size) public GameBoard() { creatingArray(10, 10); } // Constructor with custom rows and columns for non-standard boards public GameBoard(int row, int column) { creatingArray(row, column); } // Constructor for a square grid (rows = columns) public GameBoard(int size) { creatingArray(size, size); } // Helper method to initialize the 2D array (private since it's only used internally) private void creatingArray(int rows, int columns) { // Initialize the outer array with the specified number of rows values = new int[rows][columns]; // Optional: fill the grid with a default value (0 = empty cell for your battleship game) for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { values[i][j] = 0; } } } }
Key Fixes & Notes:
- Constructor Name Correction: Changed all constructor names from
GridtoGameBoard—this is non-negotiable in Java, as constructors must match their class name to be recognized. - Completed Square Grid Constructor: The third constructor takes a single
sizeparameter and passes it tocreatingArrayfor both rows and columns, making it easy to create square boards like 7x7 or 15x15. - Added
creatingArrayImplementation: Since your code called this method but didn't define it, I added a private helper that sets up the 2D array and fills it with a default value (0 works great for representing empty cells in your battleship logic). - Access Modifier for
creatingArray: Marked it asprivatebecause it's only used by the class's constructors—no external code needs to call this directly.
Quick Usage Example:
// Create a standard 10x10 battleship board GameBoard standardBoard = new GameBoard(); // Create a custom 8x12 board GameBoard customBoard = new GameBoard(8, 12); // Create a square 7x7 board GameBoard squareBoard = new GameBoard(7);
This should get your GameBoard class fully functional for your assignment. If you need help adding other features—like placing ships, checking for hits, or rendering the board—just share more details about what you're trying to build!
内容的提问来源于stack exchange,提问作者THE JESSOP

