Question

I have an issue with an Array while developing a Bukkit Plugin. Why doesn't this work? It is supposed to check whether the player has already placed the block. It keeps on saying "Diamonds!!" ingame.

@EventHandler
public void OnPlaceofDiamond(BlockPlaceEvent e){
    Player player = e.getPlayer();
    String storage[] = new String[100];
    int i = 0;

    if(e.getBlock().getType() == Material.DIAMOND_BLOCK){
        if(Arrays.asList(storage).contains(player.getName())){
            player.sendMessage(ChatColor.BLUE + "You are on the list");
        }else{
            player.sendMessage(ChatColor.BLUE + "DIAMONDS!!");
            storage[i] = player.getName();
            i++;
        }
    }
}
Was it helpful?

Solution

It's because your creating a new storage array every time a player places a block:

@EventHandler
public void OnPlaceofDiamond(BlockPlaceEvent e){
    Player player = e.getPlayer();
    String storage[] = new String[100];

So you'll never have the complete list of players. To fix this, you should declare the Array outside of your method:

String storage[] = new String[100];

@EventHandler
public void OnPlaceofDiamond(BlockPlaceEvent e) {
    Player player = e.getPlayer();
    int i = 0;

    if(e.getBlock().getType() == Material.DIAMOND_BLOCK){
        if(Arrays.asList(storage).contains(player.getName())){
            player.sendMessage(ChatColor.BLUE + "You are on the list");
        }
        else{
            player.sendMessage(ChatColor.BLUE + "DIAMONDS!!");
            storage[i] = player.getName();
            i++;
        }
    }
}

OTHER TIPS

Your issue is that every time the BlockPlaceEvent event is called, an entirely new storage array is created. If you want storage to not be recreated on every event call, you have to place it outside of the method declaration like this:

String storage[] = new String[100];

@EventHandler
public void OnPlaceofDiamond(BlockPlaceEvent e) {
    Player player = e.getPlayer();
    int i = 0;
    //The rest of your code below
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top