I feel like I'm overlooking something simple here, but my for loop is never being executed. Here's the block that's the problem: Code: Location xPlus = new Location(p.getWorld(), x + 1, newYInt, z); xPlus.getBlock().setType(Material.CHEST); System.out.println("Getting blocks works"); Chest chestBlock = (Chest) xPlus.getBlock() .getState(); for (int i = chestBlock.getInventory().getSize(); i < 11; i++) { int r = (int) (Math.random() * 10); System.out.println("For loop works"); if (r == 0) { chestBlock .getInventory() .addItem( new ItemStack( Material.GOLDEN_APPLE)); System.out.println("Golden apple!"); } else { chestBlock.getInventory().addItem( new ItemStack(Material.APPLE)); System.out.println("Regular apple :/"); } } Help please!
I'm really confused why you have that int variable "r". If you're trying to add an item to the chest, it's not adding anything because you're getting a random number, then checking if it's 0. Thus meaning if it's not 0, nothing will happen. Also why exactly do you need the loop for?
Are we to assume that you are seeing "Getting blocks works" but not "For loop works"... or are you doing this whole thing in an eventhandler that isn't registered at all, or has the @Eventhandler annotation and seeing nothing. When your loop is not running, are you getting any errors in the console - index out of bounds? EDIT: @Ace - he probabably wants a 10% chance of doing the spawn, as int of (rnd *10) would be 0 to 9... Printout what the value of chestBlock.getInventory().getSize() is before the loop starts You might be thinking something backwards based on that number...
@AcePilot10 I'm generating a random number from 0-9, and depending on which number it returns, it returns a golden apple or a regular apple. The else would cover all numbers from 1-9. The for loop is because I want to add 10 items to the chest. @Boomer Sorry if I wasn't clear, I can see "getting block works" but not "for loop works". This is all in a void called "spawnDrop" which is activated in a PlayerJoinEvent. The entire block works except for the for loop. I'm not currently getting any errors in console. As what you said and what @Permeer said, the value of the chest must be 27, therefore my loop will never run. What I'm trying to do is run my loop until the chest has 10 items in it(I will be clearing the chest's inventory before the loop is run). So, how might I get how many items a chest contains? I figured to try Code: chestBlock.getInventory().getContents().length; but it didn't seem to work either. Anyone know how to get the amount of items in a chest?
@ark9026 1. Create a new int 2. Loop Through all the inventory slots 3. Check if slot is not null 4. increase the new int the new int will be the contents lenght (Sorry for my english)