编辑:@奥斯卡洛佩兹
我已经添加了您指定的代码,现在有以下内容: import java.util.HashMap; 导入 java.util.Map;
public class Character{
public String name;
private HashMap<String, String> stats;
public Character(String charName){
name = charName;
stats.put("Strength", "5");
stats.put("Dexterity", "5");
stats.put("Constitution", "5");
stats.put("Intelligence", "5");
stats.put("Strength", "5");
stats.put("Wisdom", "5");
}
public String getStat(String name) {
return stats.get(name);
}
public static void main(String[] arguments){
Character tanis = new Character("Tanis");
System.out.println(tanis.getStat("Dexterity"));
}
}
它似乎编译正确,但它不喜欢我尝试将stats.put
事物放入哈希图中的方式,我应该如何去做呢?
import java.util.HashMap;
public class Character{
public String name;
private static HashMap<String, String> stats;
public Character(String charName){
name = charName;
stats = new HashMap<String, String>();
stats.put("Strength", "5");
stats.put("Dexterity", "5");
stats.put("Constitution", "5");
stats.put("Intelligence", "5");
stats.put("Strength", "5");
stats.put("Wisdom", "5");
}
public String getStat(String statName) {
return stats.get(statName);
}
public static void changeStat(Character character, String statName, String newStatValue) {
character.stats.put(statName, newStatValue);
}
public static void main(String[] arguments){
Character tanis = new Character("Tanis");
System.out.println(tanis.getStat("Dexterity"));
Character xander = new Character("Xander");
changeStat(xander, "Dexterity", "7");
System.out.println(xander.getStat("Dexterity"));
System.out.println(tanis.getStat("Dexterity"));
}
}
//Prints out
//5
//7
//7
为什么 tanis.getStat 更改为 7?