我正在用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]);
}
}
}
}
基本上,這裏的想法是爲具有輸入的數據,由「=」,並分割成陣列分爲靜態常量:
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;
的問題是,海峽[0]心不是被公認的價值,但是當我打印值到屏幕上,他們是完全一樣的if語句是什麼 正在找。任何人都可以給我一個關於這裏發生了什麼問題的想法嗎?我正走在正確的道路上嗎?
.equals(),.equals(),.equals() –
鑑於語法已經多麼接近,爲什麼不能忘了逗號和只把你的數據作爲屬性文件? (請參閱'java.util.Properties') – Alnitak