I am currently working with 2D arrays, and while I find them simple to work with, I often face challenges with creating borders for them and the steps to approach it. For example, I'm redoing a Battleship game I made in python. The python version doesn't have a border, but for the java version, I want to tackle the challenge.
I have tried creating the border in the method that initializes the board, but that lead to formatting issues when I called the board in the main method. Now I'm handling the border in the main with a nested for-loop, and while the results have gotten better, the border is still incomplete. I'm trying to create this border I found online:
+---+
| |
+---+
But I haven't been successful. Here is my code:
public static String[][] Battlefield() {
int row;
int col;
int cap_start = 65;
//Makes board
String[][] BattleBoard = new String[11][11];
for (row = 0; row < BattleBoard.length; row++) {
for (col = 0; col < BattleBoard[row].length; col++) {
if (row == 0) {
//System.out.print(
// " " + Character.toString((char) cap_start) + " ");
BattleBoard[row][col] =
" " + Character.toString((char) cap_start) + " ";
cap_start++;
} else if (col == 0) {
//Gives us 0-9
//System.out.print(Integer.toString(row - 1) + " ");
BattleBoard[row][col] = (Integer.toString(row - 1)) + " ";
} else {
//System.out.print(" ");
BattleBoard[row][col] = " ";
}
}
}
return BattleBoard;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Scanner colInput = new Scanner(System.in);
Scanner rowInput = new Scanner(System.in);
String player_col = "";
String player_row = "";
String[][] gameBoard = Battlefield();
for (int row = 0; row < gameBoard.length; row++) {
for (int col = 0; col < gameBoard[row].length; col++) {
System.out.print(gameBoard[row][col] + " |");
if (row <= gameBoard.length - 1)
System.out.print("+---+");
}
System.out.println();
}
}