java - 如何将Word转换为固定数字

标签 java string int

您好,我想知道如何将“英雄”这样的单词转换为给定的数字?

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;
}

然后,在您的代码中,您将:

  1. 创建英雄列表
  2. 搜索该列表以查找名称匹配的列表。
  3. 返回他们的攻击力。

例如:

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/

相关文章:

java - Android 按钮 onClick 处理程序未找到

java - 如何测试一个类的所有方法都没有在jMock中被调用?

Java读取文本并将文本数据作为整数进行操作

c++ - 如何将0x0000之类的字符串转换为int

json - 通过模型快速解析 JSON 到对象 - 解码 int/string 问题

c - C中十六进制字符串到int的转换

java - Tomcat 启动挂起

java - Pixelart 的抗锯齿算法

java - 垃圾收集器和 String.intern()

C - 如何通过系统调用打印整数?