我尝试通过这样做将字符串转换为 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 和数据值)来指定 block 的特定“类型”,则您需要拆分字符串并分别设置两个值。可能有更好的方法来使用 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!");
}
}
关于java - Spigot - 将字符串转换为 Material - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35301633/