Reputation: 37
So basically what I am trying to do is make it so every player has their own extra storage bag that they can upgrade(starting on that later), but at the moment I am stuck with this. I am making it so if the Hashmap "storage" does not contain a value, to create a new inventory and set it a value. The only problem is I cannot then use the inventory "bag" in another if statement to open it when the value is set. Here is my code :
package me.impatheimpaler.aqw;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
public class Storage implements Listener{
public me.impatheimpaler.aqw.Main plugin;
public HashMap<String, Inventory> storage = new HashMap<String, Inventory>();
public Storage(Main main) {
plugin = main;
}
@EventHandler
public void onInteract(PlayerInteractEvent e) {
if (!(e.getItem().getType() == Material.CHEST)) return;
if (!(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return;
if (e.getItem().getItemMeta().hasLore() &&
e.getItem().getItemMeta().getLore().contains(ChatColor.GREEN + "A bag for extra storage.")) {
if (storage.containsKey(null) && storage.containsValue(null)) {
Inventory bag = Bukkit.getServer().createInventory(e.getPlayer(), 9, "Storage");
storage.put(e.getPlayer().getName(), bag);
}
if (storage.contains(e.getPlayer().getName(), bag)) {
//Here is the error, as I cannot use the value "bag", because it cannot be
accessed from another if statement.
}
}
}
}
Upvotes: 0
Views: 97
Reputation: 23596
You could just declare bag
outside of the if statement, then set it inside of the statement:
Inventory bag;
if(storage.containsKey(null) && storage.containsValue(null)){
//code
}
So, it could look something like this:
Inventory bag;
if (storage.containsKey(null) && storage.containsValue(null)) {
bag = Bukkit.getServer().createInventory(e.getPlayer(), 9, "Storage");
storage.put(e.getPlayer().getName(), bag);
}
if (storage.contains(e.getPlayer().getName(), bag)) {
//use "bag" however you want
}
Also, instead of checking if storage.containsKey(null)
, to check if the player's name NOT is in the HashMap
, you should use:
if(!storage.containsKey(e.getPlayer().getName()){
Doing storage.containsKey(null)
will check if the map has null
as a key, it won't find anything out about the player
Upvotes: 1