我正在尝试创建一个带有括号的对象,就像数组一样,但我希望它是一个对象,以便我可以拥有诸如 hasLocation 或 returnMap 等方法嗯>。我想要成为对象的数组称为Map。在创建 Map 对象之前我的代码如下:
public class Main {
public static void main(String[] args) {
gamePreset();
}
public static void gamePreset(){
/**
* Creating Locations
* It is important to note that the yPos starts in the left corner of the map and increases southward.
* (0,0)|(1,0)|(2,0)
* -----------------
* (0,1)|(1,1)|(2,1)
* -----------------
* (0,2)|(1,2)|(2,2)
*/
Location location00 = new Location(0,0,entities00,"This is location 00. Welcome to the map.");
Location location01 = new Location(0,1,entities01,"This is location 01. You are south of location 00.");
Location location11 = new Location(1,1,entities01,"This is location 11. You are southeast of location 00.");
Location location10 = new Location(1,0,entities01,"This is location 10. You are east of location 00.");
//Adding Locations to the Map Array
Location[][] map = new Location[2][2];
map[0][0] = location00;
map[0][1] = location01;
map[1][1] = location11;
map[1][0] = location10;
System.out.println(returnMap(map));
}
public static String returnMap(Location[][] map){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < map.length; i++){
for(int j = 0; j < map[i].length; j++){
sb.append("(" + map[i][j].getXPos() + "," + map[i][j].getYPos() + ")");
sb.append(" ");
}
sb.append("\n");
}
return sb.toString();
}
public static boolean hasLocation(Location[][] map, int xPos, int yPos){
if(map[xPos][yPos]!=null){
return true;
}
return false;
}
Location 包含一个 xPosition、一个 yPosition、一条消息以及该位置处的对象列表。我想要的是一个仍然具有像我的数组一样的括号位置的对象: Location[][] map = new Location[2][2]; 这可能吗?有更好的方法吗? 我尝试创建一个构造函数,但我不确定如何继续:
public class Map {
public Location[][] map;
Map(int xHeight, int yHeight, String mapName){
Location[][] mapName = new Location[xHeight][yHeight];
}
.....methods like returnMap.....
}
如果一切按我的方式进行,我的代码将如下所示:
Map newMap = new Map(2,2,"map00");
newMap[1][1] = location00;
最佳答案
只需在 Map 类中声明一个新函数? 像这样的事情怎么样:
public void setLocation(int x, int y, Location loc){
this.map[x][y] = loc;
}
关于java - 使带有位置括号的对象类似于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609880/