您好,我想知道如何将“英雄”这样的单词转换为给定的数字?
if(Hero.equalsIgnoreCase("Steve")) {
// turns string hero into Steve Attack value
}
else if(Hero.equalsIgnoreCase("Akiro")) {
// turns string hero into Akiro Attack value
}
else if (Hero.equalsIgnoreCase("Big Willie")) {
// turns string hero into Big WIllie Attack Value
}
else if (Hero.equalsIgnoreCase("Shourya")) {
// turns hero into Shourya Attack value
}
最佳答案
有几种方法可以解决这个问题。
最简单(也是最 OOP)的方法是简单地创建一个类 Hero
并包含一个伤害字段,如下所示:
public class Hero {
String name;
int attackDamage;
}
然后,在您的代码中,您将:
- 创建英雄列表
- 搜索该列表以查找名称匹配的列表。
- 返回他们的攻击力。
例如:
List<Hero> list = new ArrayList<>();
list.add(...); // create a few heroes and add them to the list
...
String name = "hero name";
// now search for a hero and return their attack damage
int damage = list.stream() // convert into a stream for easier searching
.filter(hero -> hero.name.equalsIgnoreCase(name)) // find only heroes with the correct name
.map(hero -> hero.attackDamage) // get damage
.findFirst() // check if they exist
.orElse(-1); // return -1 if no hero found
关于java - 如何将Word转换为固定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59871006/