我有一个叫做game的类,在其中我使用默认的构造函数来创建和初始化另一个类的2D对象数组。但是,在另一种用于操纵2D数组中的对象变量的方法中,遇到一个错误,指出“ gameBoard(对象)无法解析为变量”。仅在第二种方法的底部遇到错误。
public game() {
// Start initialize game board
grid[][] gameBoard = new grid[9][9];
gameBoard[0][0] = new grid(" ", "N", true);
gameBoard[0][1] = new grid("A", "N", true);
gameBoard[0][2] = new grid("B", "N", true);
gameBoard[0][3] = new grid("C", "N", true);
gameBoard[0][4] = new grid("D", "N", true);
gameBoard[0][5] = new grid("E", "N", true);
gameBoard[0][6] = new grid("F", "N", true);
gameBoard[0][7] = new grid("G", "N", true);
gameBoard[0][8] = new grid("H", "N", true);
gameBoard[1][0] = new grid("1", "N", true);
gameBoard[2][0] = new grid("2", "N", true);
gameBoard[3][0] = new grid("3", "N", true);
gameBoard[4][0] = new grid("4", "N", true);
gameBoard[5][0] = new grid("5", "N", true);
gameBoard[6][0] = new grid("6", "N", true);
gameBoard[7][0] = new grid("7", "N", true);
gameBoard[8][0] = new grid("8", "N", true);
for (int x = 1; x < 9; x++) {
for (int y = 1; y < 9; y++) {
gameBoard[x][y] = new grid();
}
}
// End
}
public void placeUserShips() {
// Start place user ships
for (int x = 1; x <= 6; x++) {
System.out.print("Enter the coordinates of your ship #" + x + ": ");
String cell = input_scanner.nextLine();
String letter = cell.substring(0, 1);
switch (letter) {
case "A":
letterCol = 1;
break;
case "B":
letterCol = 2;
break;
case "C":
letterCol = 3;
break;
case "D":
letterCol = 4;
break;
case "E":
letterCol = 5;
break;
case "F":
letterCol = 6;
break;
case "G":
letterCol = 7;
break;
case "H":
letterCol = 8;
break;
default:
letterCol = 0;
break;
}
number = Integer.parseInt(cell.substring(1, 2));
if (gameBoard[letterCol][number].type == "" && number >= 1 && number <= 8) {
gameBoard[letterCol][number].type = "s";
} else {
System.out.println("Sorry, those coordinates are already in use. Try again.");
x -= 1;
}
}
// End
}
答案 0 :(得分:0)
就像问题Java, “Variable name” cannot be resolved to a variable中一样,当您引用未定义的变量(或超出范围)时,会发生这种错误。
您可以在gameBoard
中构造game()
,然后将其返回到placeUserShips()
:
public grid[][] game() {
// Start initialize game board
grid[][] gameBoard = new grid[9][9];
// ...
return gameBoard;
}
public void placeUserShips() {
// Start place user ships
grid[][] gameBoard = game();
// ...
}
或使用全局变量(在main
中,您应先调用game
)
private grid[][] gameBoard;
public void game() {
// Start initialize game board
gameBoard = new grid[9][9];
// ...
}
public void placeUserShips() {
// Start place user ships
// ...
}