在java中使用字符串加载变量

在java中使用字符串加载变量,java,loading,tile,Java,Loading,Tile,基本上,我在游戏中加载关卡时遇到了问题,因为加载瓷砖时出现了问题。我不明白的是,如何让程序将磁贴的类型保存为字符串,例如“water”或“grass”,然后从这些字符串加载磁贴。下面是tiles代码的一个示例: Example = new TileType("Texture.png", Material.Mat, True, True, "Example"); 第一个值是纹理位置,第二个值是材质,第三个值是瓷砖是否可以销毁,第四个值是NPC是否可以通过瓷砖,最后一个值是瓷砖在标高数据中保存的内

基本上,我在游戏中加载关卡时遇到了问题,因为加载瓷砖时出现了问题。我不明白的是,如何让程序将磁贴的类型保存为字符串,例如“water”或“grass”,然后从这些字符串加载磁贴。下面是tiles代码的一个示例:

Example = new TileType("Texture.png", Material.Mat, True, True, "Example");
第一个值是纹理位置,第二个值是材质,第三个值是瓷砖是否可以销毁,第四个值是NPC是否可以通过瓷砖,最后一个值是瓷砖在标高数据中保存的内容

以下是游戏将瓷砖保存为的内容:

<tile x="0" y="0" type="Example" />

我试图做的是创建一个方法,该方法获取字符串并查找使用它的磁贴。有人能帮我做这个吗?

用电脑怎么样


(根据要求将评论作为答案发布。)

1.更好地使用收藏
地图


<强> 2。< /强>考虑如下…code>HashMap

对于数字变量,可以使用

String s = readIntFromFile(); //Read a number
try
{
    int x = Integer.parseInt(s); //Get an integer from the file
}
catch(NumberFormatException e)
{
    //if parseInt fails, we end up here
}
对于字符串,这里有一个想法:

static final String[] tileTypes = {"Example", "Example2"};
private static int findTileType(String type)
{
    for(int i = 0; i < tileTypes.length; i++)
    {
        if(type.equals(tileTypes[i])) return i;
    }
    return -1;
}

public TileType makeTile(String type)
{
    int t = findTileType(type);
    switch(t)
    {
        case 0: 
            return example;
        case 1: 
            return example2;
    }
    return null;
}

static final TileType example = new TileType(/*...*/);
static final TileType example2 = new TileType(/*...*/);
static final String[]tileTypes={“Example”,“Example2”};
私有静态int findTileType(字符串类型)
{
for(int i=0;i
好吧,你明白了。也许不是最好的解决方案,但它会奏效


一年多后编辑:哎呀,忘了让FindFileType保持静态。

我会创建一个名为Tile的类

公共类平铺
{
私人材料;
私有布尔值被破坏;
私有布尔mCanBeWalkedOn;
私有字符串mLevelSaveName;
//接球手和接球手
}
然后使用类似这样的方法访问它们:

private HashMap<String, Tile> mTiles;
私有HashMap mTiles;

使用
地图如何
?回答马特-否则我会;)@马特波尔我和阿米拉法尼在一起;)@AmirAfghani&MadProgammer:完成了。如果要将对象序列化为XML,则需要一个XML解析器来再次读取它们。试试dom4j的