Java名称具有变量名称的对象

时间:2013-02-03 12:55:29

标签: java minecraft

所以我正在为Minecraft制作一个插件。它基本上是一个团队插件。我需要做的是,能够创建多个团队,但我似乎无法弄清楚如何将对象名称更改为玩家选择的团队名称。这就是我的意思:

if (l.equalsIgnoreCase("NewTeam")) {
    teamName= args[0]; // This is the players chosen team name
     Team newTeam = new Team(teamName, sender);
     newTeam.addPlayer(sender);

由于这是一个服务器插件,它必须处理多个团队,这意味着它创建了许多团队对象,但所有团队对象都是对象名称newTeam。有谁知道我能做到这一点的更好方法?感谢。

2 个答案:

答案 0 :(得分:1)

您正在搜索团队名称到团队对象的映射? 然后,您可以按如下方式执行此操作:

Map<String,Team> teams = new TreeMap<String,Team>();

//Returns the team for 'teamName' or creates one, if it doesn't exist
public Team getTeam(String teamName)
{
    Team team = teams.get(teamName);
    if(team == null)
    {
        team = new Team(teamName,sender); //is 'sender' specific for a team??
        teams.put(teamName,team);
    }
    return team;
}

答案 1 :(得分:0)

我假设你正在使用Bukkit API,而且这是在CommandExecutor的onCommand方法中完成的,所以这里应该是这样的:

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
   if(cmd.getName().equalsIgnoreCase("newteam")){ //Make sure this is the right command
      if(args.length == 0) //If the sender hasn't included a name...
         sender.sendMessage("You need to include a team name!"); //Tell them they need to
      else{ //Otherwise...
         Team newTeam = new Team(args[0]); //Create a new team with the designated name
         if(sender instanceof Player) //If the sender is a player (could be console)...
            newTeam.addPlayer((Player) sender); //Add them to the team
         /*
          * Insert some code to save/store the newly created team here
          */
      }
      return true; //Return (for Bukkit's benefit)
   }
}