我正在製作一個簡單的遊戲,並將一個帶有武器屬性的XML文件加載到遊戲中使用的武器陣列中。統計數據和武器對象都被正確地讀取和填充,直到'try'語句結束,然後用最後一次讀取武器元素的值重寫整個武器陣列。我不能爲了我的生活找出爲什麼它決定突然重寫一切,幫助將不勝感激,因爲我覺得這是一個菜鳥的錯誤!Java XML解析,正確讀取值到數組然後用最後的值覆蓋整個數組?
private void populateWeaponArray(NodeList listOfWeapons){
String weaponName;
int[] stats = new int[10];
int weaponClass;
boolean twoHanded;
try{
for(int i=0;i<listOfWeapons.getLength();i++){
//Get individual weaponNode
Node weaponNode = listOfWeapons.item(i);
//Convert to element to provide more methods and access node information
//Element is just an interface that inherits from node
Element weaponElement = (Element) weaponNode;
//Retrieve Attribute Values level, class
stats[9] = Integer.valueOf(weaponElement.getAttribute("level"));
weaponClass = Integer.valueOf(weaponElement.getAttribute("class"));
//Get a list of all stats of weapon
NodeList statList = weaponElement.getChildNodes();
//populate the stat[] with all numbers
for(int s=0;s<9;s++){
stats[s] = Integer.valueOf(statList.item(s).getFirstChild().getNodeValue());
}
//Retrieve name and twohanded from xml
weaponName = statList.item(9).getFirstChild().getNodeValue();
twoHanded = Boolean.valueOf(statList.item(10).getFirstChild().getNodeValue());
//Construct weapon object from values
weapons[i] = new Weapon(weaponName, weaponClass, twoHanded, stats);
System.out.println(weapons[i]); //Weapon objects here all display correctly
}
}catch(Exception e){
System.out.println("weaponHandler " + e.getMessage());
}
for(int i = 0;i<weapons.length;i++){
System.out.println(weapons[i]); //Suddenly Weapon objects here all have the same stats?
}
調用嘗試{}都揭示了他們有從XML中正確的統計結束前每件武器的覆蓋toString方法,但該塊已經結束的那一刻,他們都具有相同的統計數據。如果你需要知道其他任何只是噱頭喊,任何幫助,非常感謝:)
當時,儘管提供了答案,我看不出我做錯了什麼 - 我只是不明白。一年後,我重新登錄並看到這個問題,我完全理解!再次感謝您的回答 - 當我今晚讀到它時,我對自己的問題進行了翻閱。很高興知道有一個支持社區的初學者:)再次感謝 – anoTHErNoob