我正在用Java创建一个3D游戏,我希望能够接收玩家信息,并将其保存到文本文件中。我理解数据库可能更优,但是出于我自己的测试目的,文本文件应该符合我的需要。我的文本文件包括以下内容:
username=kyle13524,
player_health=100,
player_mana=100,
player_position_x=100,
player_position_y=100,
player_position_z=100,
player_money=2149000
我正在使用这个parsePlayerData方法:
private void parsePlayerData() {
String filestring = null;
List<String> playerData = new ArrayList<String>();
ListIterator<String> li = playerData.listIterator();
try {
BufferedReader br = new BufferedReader(new FileReader("res/data/playerdata.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
filestring = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(filestring != null) {
String[] parts = filestring.split(",");
String[] str = null;
for(String part : parts) {
playerData.add(part);
}
for(String string : playerData) {
str = string.split("=");
if(str[0] == "username") {
PLAYER_NAME = str[1];
}
if(str[0] == "player_health") {
PLAYER_HEALTH = Integer.parseInt(str[1]);
}
if(str[0] == "player_mana") {
PLAYER_MANA = Integer.parseInt(str[1]);
}
if(str[0] == "player_position_x") {
PLAYER_X = Float.parseFloat(str[1]);
}
if(str[0] == "player_position_y") {
PLAYER_Y = Float.parseFloat(str[1]);
}
if(str[0] == "player_position_z") {
PLAYER_Z = Float.parseFloat(str[1]);
}
}
}
}
基本上,这里的想法是输入数据,由&#39; =&#39;分成数组。并组织成静态常量:
public static String PLAYER_NAME;
public static int PLAYER_HEALTH;
public static int PLAYER_MANA;
public static float PLAYER_X;
public static float PLAYER_Y;
public static float PLAYER_Z;
public static int PLAYER_MONEY;
问题是str [0]没有被识别为值,但是当我将值打印到屏幕时,它们与if语句正在寻找的完全相同。谁能给我一个关于这里出了什么问题的想法?我走的是正确的道路吗?
答案 0 :(得分:0)
您应该使用==
来比较字符串,而不是使用equals
方法,例如。
str[0] == "username"
应该成为
str[0].equals("username")