I tried to cast a String to a Material
by doing this:
for (Material ma : Material.values()) {
if (String.valueOf(ma.getId()).equals(args[0]) || ma.name().equalsIgnoreCase(args[0])) {
}
}
If args[0]
is a String like 2
or grass
it works very well, but how can I cast for example 41:2
to Material
?
Thank you for your help and sorry for my bad English ;)
In the case of the notation you're describing which uses two magic values (the type ID and data value) separated by a colon to specify the certain "type" of a block, you'll need to split the string and set the two values separately. There might be a nicer way to convert the magic value data byte using the MaterialData
class, but it's probably still easier to use the direct and deprecated method of block.setData(byte data)
. So if args[0]
contains a colon, split it and parse the two numbers. Something along the lines of this could work for you:
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!");
}
}