2015-05-20 33 views
0

所以基本上我所要做的就是讓每個玩家都有自己的額外存儲包,以便升級(從此開始),但目前我被困在這個。我是這樣做的,所以如果哈希表「存儲」不包含值,要創建一個新的清單併爲其設置一個值。唯一的問題是我不能在另一個if語句中使用庫存「bag」來在設置值時打開它。這裏是我的代碼:在另一個if語句中獲取庫存

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. 

     } 
    } 

} 

} 

回答

1

你可以只聲明bag外的if語句中,然後將其設置語句的內部:

Inventory bag; 
if(storage.containsKey(null) && storage.containsValue(null)){ 
    //code 
} 

因此,它可能是這個樣子:

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 
} 

另外,代替檢查是否storage.containsKey(null),檢查玩家的名字不是是否在HashMap,你應該使用:

if(!storage.containsKey(e.getPlayer().getName()){ 

storage.containsKey(null)將檢查該映射null作爲重點,也不會發現什麼了有關球員