Q:

How to access variables in for loops

I have a for loop that counts the number of blocks in a players inventory.
for (int i = 36; i < 45; i++) {
    final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();

    if (itemStack != null && itemStack.getItem() instanceof ItemBlock) {
        Block block = ((ItemBlock) itemStack.getItem()).getBlock();
    }
}

I want to use the block variable I used there but I cant seem to access, even if it is in the same function.
Thanks,

A:

Your block variable is defined in an if statement, if the condition isn't met the variable may not have been created

A:

every local variable is visible where it is defined, if you need to have access after your loop, define that in the proper place.
as an example:
Block block;
for (int i = 36; i < 45; i++) {
    final ItemStack itemStack = 
        mc.thePlayer.inventoryContainer.getSlot(i).getStack();

    if (itemStack != null && itemStack.getItem() instanceof ItemBlock) {
        block = ((ItemBlock) itemStack.getItem()).getBlock();
        // maybe a break command is needed also (check the requirements) 
    }
}

this way, after the loop, you can check whether block has a value or not.

