我正在制作一个简单的游戏,并将带有武器统计信息的 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?
}
在 try{} 结束之前调用每个武器的被覆盖的 toString 方法都会显示它们具有来自 XML 的正确统计信息,但是当块结束时,它们都具有相同的统计信息。如果您需要了解其他任何信息,请大声喊叫,非常感谢您的帮助:)