所以我正在为Android安装一个相当粗糙的RPG游戏。它更像是测试我的技能而不是其他任何东西。我正在玩球员课,我有这样的统计数据:
int health = 3;
int strength = 3;
int knowledge = 3;
int resolve = 3;
int empathy = 3;
int xp = 0;
int statpoints = 0;
int level = 1;
int cap = 2 * level;
int capCounter = 0;
int TotalHealth = 2 * health + level;
稍后在代码中我有一个方法是接受stat的名称并尝试增加它,如果它可以
private void updateStat(String stat) {
if (capCounter < cap) {
if (statpoints >= 2 * cap * level) {
capCounter++;
if (capCounter <= cap) {
statpoints = 0;
}
}
else {
System.out.print("You don't have enough points");
}
}
else {
System.out.print("Yout must level up first");
}
}
那个大空格代表一个代码区域,我想要解析字符串“stat”并从中提取我正在尝试更新的stat的名称,然后将该stat更新为1.有没有办法去做这个?
哦,System.out.print调用目前用于测试目的。只要我能在Android Studio的更新版本中弄清楚如何使用Toasts,它们就会被Toast取代。我以前习惯调用makeText的方式一直都是错误的。
答案 0 :(得分:0)
最简单的解决方案是使用apache BeanUtils library和PropertyUtils类。
您需要的代码是
PropertyUtils.setSimpleProperty(yourPlayer, "yourField", "yourValue");
最长的答案是使用de reflec API,它允许您操作对象,如读/写属性,注释等等:Javadoc Here enter link description here
另一个信息,你制作和android应用程序,反映api的使用是出于性能原因而不鼓励的。也许最好的解决方案是拥有一个包含所有不同数据的地图
Map<String, Integer> statsValue = new HashMap<>();
statsValue.put("health", 3);
statsValue.get("health");
答案 1 :(得分:0)
考虑到您有很多统计信息,并且您希望通过stat的名称而不是索引号来访问它们,您应该使用已定义的数据结构,而不是数十个变量。
已经推荐了许多解决方案,但是最快且最好学习的解决方案之一是 HashMap 。它允许您按键搜索数据(即&#39; health&#39;);
答案 2 :(得分:0)
为什么不使用HashMap
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("health", 1);
hashMap.put("strenght", 1);
.
.
.
然后你可以通过像这样的字符串统计获取值
hashMap.get(StatString)
祝你好运!