How to check if item / block

Hey,
I want to check, if the item in player’s hand is a block or an item and output infos about blocks / items.

I have following code (outputs block infos)

if (player.getItemInHand().isPresent()) {
    //player.getItemInHand().get().getItem().getId();
    BlockState blockState = player.getItemInHand().get().getItem().getBlock().get().getDefaultState();
    //send message
    userManager.sendLittleInfo(blockState.toString(), player);
}

Because I want to output infos about items and blocks, i have to check, if the itemInHand is a block or an item…

If it’s a block:
BlockState blockState = player.getItemInHand().get().getItem().getBlock().get().getDefaultState();
… and if it’s an item (???)

Thanks :slight_smile:

getBlock() returns an optional, which means that it will throw an error if the ItemStack is not a block, because you are not checking if it exists first.

If getBlock is present, the ItemStack is a block. If not, then it is an item.

Optional<ItemStack> optionalStack = player.getItemInHand();
if(optionalStack.isPresent()) {
    ItemStack stack = optionalStack.get();
    if(stack.getItem().getBlock().isPresent()) {
        // Is a block
    } else {
        // Is an item
    }
} else {
    // Player is not holding an item
}
1 Like