【发布时间】:2018-09-14 21:28:52
【问题描述】:
假设我正在构建一个国际象棋游戏并创建棋盘空间对象。我正在创建这样的对象,棋盘上的所有空间正好是 64:
BoardSpace a1 = new BoardSpace("black", 1, 1, true);
这是我为 BoardSpace 对象创建的类:
public class BoardSpace {
String color;
int x_pos;
int y_pos;
boolean occupied;
//constructor
public BoardSpace (String color, int x_pos, int y_pos, boolean occupied) {
this.color = color;
this.x_pos = x_pos;
this.y_pos = y_pos;
this.occupied = occupied;
}
}
在棋盘上移动棋子之前,我创建了所有 BoardSpace 对象。我的棋子对象每个都有一个 x 位置和 y 位置。我要做的是将它们的坐标转换为 BoardPiece 名称,然后从该名称中检索先前创建的 BoardPiece 对象。
这就是我想做的:
static String get_BoardSpace_color(int x_pos, int y_pos){
int modified_x = x_pos + 96; //adjusting for ASCII
char c = (char)(modified_x);
String space_name = ""+c+y_pos;
BoardSpace piece = (BoardSpace)(space_name); //PROBLEM AREA
return piece.color;
}
我怎样才能使用已经存在的对象名称的正确字符串表示来实际检索该对象?
【问题讨论】:
-
对象没有名字。为什么不创建 BoardSpace 的 8x8 2D 数组,例如称为
grid并简单地获取grid[x_pos][y_pos]对象? -
我建议您使用
enum而不是string作为颜色变量 -
您无权访问变量的名称。与其尝试通过变量名访问东西,不如将实例存储在某个集合中。像
List或者可能是一个数组。然后在那里访问它们,例如list.get(4)或array[4]。