我试图通过执行以下操作将字符串转换为Material
:
for (Material ma : Material.values()) {
if (String.valueOf(ma.getId()).equals(args[0]) || ma.name().equalsIgnoreCase(args[0])) {
}
}
如果args[0]
是类似于2
或grass
的字符串,则效果很好,但是如何将例如41:2
强制转换为Material
?
谢谢您的帮助,对不起我的英语不好;)
在您要描述的符号的情况下,它使用两个魔术值(类型ID和数据值)并用冒号分隔来指定块的特定“类型”,您需要将字符串拆分并设置两个值分开。使用MaterialData
类转换魔术值数据字节可能是更好的方法,但使用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!");
}
}