Cannot cast to chest error

Discussion in 'Plugin Development' started by superchris05326, Apr 26, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    superchris05326

    I am trying to 1) Create a chest at a certain block 2)Get a random item from the config and 3)Put said item into the chest. When I use this code I get an error in the task saying that I cannot cast the block to chest. Could you explain to me why this doesn't work?

    Methods:
    Code:
    public static void createRandomChest(){
            Block b = getRandomBlock();
            if(b != null){
                b.setType(Material.CHEST);
                ((Chest) b).getBlockInventory().addItem(ConfigManager.getRandomItem());
            }
        }
    
        public static Block getRandomBlock(){
            if(chests.size() != 0){
                String randomName = (String) chests.keySet().toArray()[new Random().nextInt(chests.keySet().size())];
                return chests.get(randomName).getBlock();
            }
            return null;
        }
    ConfigManager.class:
    Code:
    private static List<Integer> i;
       
        public ConfigManager(Loot plugin){
            i = plugin.getConfig().getIntegerList("Items");
        }
       
       
       
        @SuppressWarnings("deprecation")
        public static ItemStack getRandomItem(){
            Random random = new Random();
            int rn = random.nextInt(i.size());
            return new ItemStack(Material.getMaterial(i.get(rn)));
        }
    Repeating task:
    Code:
    BukkitScheduler scheduler = getServer().getScheduler();
            scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
                @Override
                public void run() {
                    LootManager.createRandomChest();
                }
            }, /*6000*/100, 100/*6000*/);
     
  2. Offline

    meguy26

    Chests are a more advanced form of a block, they are in fact block states:
    Code:
    //Does not work because chests are not blocks
    ((Chest) b).getBlockInventory().addItem(ConfigManager.getRandomItem());
    
    //Hopefully works because chests are BLOCK STATES
    ((Chest) b.getState()).getBlockInventory().addItem(ConfigManager.getRandomItem());
     
Thread Status:
Not open for further replies.

Share This Page