Spigot - 将字符串转换为 Material - Java

Spigot - Cast String to Material - Java

我试图通过这样做将字符串转换为 Material

for (Material ma : Material.values()) {
    if (String.valueOf(ma.getId()).equals(args[0]) || ma.name().equalsIgnoreCase(args[0])) {
    }
}

如果 args[0] 是一个类似于 2grass 的字符串,它工作得很好,但是我如何将 41:2 转换为 Material

感谢您的帮助,抱歉我的英语不好 ;)

在您所描述的符号的情况下,它使用两个用冒号分隔的魔术值(类型 ID 和数据值)来指定块的某些 "type",您需要拆分字符串并分别设置两个值。使用 MaterialData class 可能有更好的方法来转换魔法值数据字节,但使用 block.setData(byte data) 的直接和弃用方法可能仍然更容易。因此,如果 args[0] 包含冒号,则将其拆分并解析这两个数字。类似于此的内容可能对您有用:

if (arguments[0].contains(":")) { // If the first argument contains colons
    String[] parts = arguments[0].split(":"); // Split the string at all colon characters
    int typeId; // The type ID
    try {
        typeId = Integer.parseInt(parts[0]); // Parse from the first string part
    } catch (NumberFormatException nfe) { // If the string is not an integer
        sender.sendMessage("The type ID has to be a number!"); // Tell the CommandSender
        return false;
    }
    byte data; // The data value
    try {
        data = Byte.parseByte(parts[1]); // Parse from the second string part
    } catch (NumberFormatException nfe) {
        sender.sendMessage("The data value has to be a byte!");
        return false;
    }

    Material material = Material.getMaterial(typeId); // Material will be null if the typeId is invalid!

    // Get the block whose type ID and data value you want to change

    if (material != null) {
        block.setType(material);
        block.setData(data); // Deprecated method
    } else {
        sender.sendMessage("Invalid material ID!");
    }

}