I'm writing a simple program that displays a 2D array. User will be given 4 options to choose from, but for simplicity sakes of this question, I rewrote the program so there's only 2 option enclosed in the switch, and that the second option will always be chosen. The code does not print anything, it only prints "This is your array :". I'm seeing "Duplicate local variable board" in my errors page but I do not know how to fix this.
Here is my code:
public class Apples {
static char[][] createBoard(int boardType) {
char[][] board = new char[8][10];
switch (boardType) {
case 1:
char board[][] = {
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'},
{'1', '#', '#', '#', '-', '@', '-', '#', '#', '#'},
{'2', '#', '#', '-', '@', '@', '@', '-', '#', '#'},
{'3', '#', '-', '@', '@', '-', '@', '@', '-', '#'},
{'4', '-', '@', '@', '@', '@', '@', '@', '-'}};
break;
case 2:
char board[][] = {
{' ', '1', '2', '3', '4', '5'},
{'1', '-', '-', '-', '-', '-'},
{'2', '-', '@', '@', '@', '-'},
{'3', '-', '-', '@', '-', '-'},
{'4', '-', '-', '@', '-', '-'},
{'5', '-', '-', '-', '-', '-'}};
break;
}
return board;
}
public static void main(String args[]) {
System.out.println("This is your array :");
char chosenboard[][] = createBoard(2);
for (int row = 0; row < chosenboard.length; row++) {
for (int column = 0; column < chosenboard[row].length; column++) {
System.out.print(chosenboard[row][column]);
}
}
}
}
Second attempt : doing "declare first, initialize later":
public class Apples {
static char[][] createBoard(int boardType) {
char[][] board;
switch (boardType) {
case 1:
board = new char[][]{
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'},
{'1', '#', '#', '#', '-', '@', '-', '#', '#', '#'},
{'2', '#', '#', '-', '@', '@', '@', '-', '#', '#'},
{'3', '#', '-', '@', '@', '-', '@', '@', '-', '#'},
{'4', '-', '@', '@', '@', '@', '@', '@', '-'}};
break;
case 2:
board = new char[][]{
{' ', '1', '2', '3', '4', '5'},
{'1', '-', '-', '-', '-', '-'},
{'2', '-', '@', '@', '@', '-'},
{'3', '-', '-', '@', '-', '-'},
{'4', '-', '-', '@', '-', '-'},
{'5', '-', '-', '-', '-', '-'}};
//here I am declaring and assigning again
break;
}
return board;
}
public static void main(String args[]) {
System.out.println("This is your array :");
char chosenboard[][] = createBoard(2);
for (int row = 0; row < chosenboard.length; row++) {
for (int column = 0; column < chosenboard[row].length; column++) {
System.out.print(chosenboard[row][column]);
}
}
}
}
The previous error of "duplicate local variable" went away, but I got a new error on my return board line. It says the "the local variable board may not have been initialized"