2014-04-05 142 views
1

我在開發Bukkit插件時遇到數組問題。爲什麼這不起作用?它應該檢查玩家是否已經放置了該塊。它不斷說「鑽石!!」在遊戲中。與陣列問題

@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++; 
     } 
    } 
} 
+0

你給總會玩家名稱添加到存儲[0],因爲每次調用該方法,'存儲[i] =播放器代碼.getName()'總是讓我成爲0.這是否可以覆蓋你想檢查的玩家名字? – LadyBernkastel

+0

爲什麼你甚至會使用一個數組來達到這個目的,當像LinkedList這樣的東西同樣適用時(並且你不會每次都把它轉換成一個列表) – Rogue

回答

0

這是因爲你的每一個玩家放置一個塊的時間創建一個新的storage數組:

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

所以你永遠不會有完整的球員名單。爲了解決這個問題,您應該聲明你的方法的Array外:

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++; 
     } 
    } 
} 
0

你的問題是,每次BlockPlaceEvent事件被調用時,將創建一個全新的storage陣列。如果你想storage不要在每次事件調用重新創建,你必須把它像這樣的方法聲明之外:

String storage[] = new String[100]; 

@EventHandler 
public void OnPlaceofDiamond(BlockPlaceEvent e) { 
    Player player = e.getPlayer(); 
    int i = 0; 
    //The rest of your code below 
}