我正在尝试创建一个带有方括号的对象,非常类似于数组,但是我希望它是一个对象,以便可以使用诸如 hasLocation 或 returnMap 的方法。 em>。我想成为对象的数组称为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;
答案 0 :(得分:1)
只需在Map类中声明一个新的Function? 那这样的事情呢?
public void setLocation(int x, int y, Location loc){
this.map[x][y] = loc;
}
答案 1 :(得分:1)
只需:
Map newMap = new Map(2,2,"map00");
newMap.map[1][1] = location00;