我试图进行聊天频道并遇到列表问题。我在执行命令时将一个元素添加到列表中,稍后我试图检查该元素是否已添加到列表中,但它始终显示它不是。
这是我的代码:
public class RpChat implements CommandExecutor, Listener {
private ArrayList<Player> ooc = new ArrayList<Player>();
private ArrayList<Player> ic = new ArrayList<Player>();
private ArrayList<Player> shout = new ArrayList<Player>();
private ArrayList<Player> whisper = new ArrayList<Player>();
public boolean onCommand(CommandSender cs, org.bukkit.command.Command cmnd, String string, String[] strings) {
Player s = (Player) cs;
if (cmnd.getName().equalsIgnoreCase("ooc")) {
s.sendMessage("Debug: OOC");
ooc.add(s);
if (ic.contains(s))
ooc.remove(s);
if (shout.contains(s))
ooc.remove(s);
if (whisper.contains(s))
ooc.remove(s);
}
return false;
}
@EventHandler
public void onPlayerChatEvent(AsyncPlayerChatEvent event) {
Player p = event.getPlayer();
Bukkit.getScheduler().scheduleSyncRepeatingTask(Dungeon.getPlugin(), new Runnable() {
public void run() {
if (ooc.contains(p)) {
event.setFormat(ChatColor.RED + "[OOC] " + ChatColor.WHITE + "%s" + ": " + "%s");
p.sendMessage("Debug Player = " + ooc.contains(p));
}
else{
p.sendMessage("Debug Player = " + ooc.contains(p));
}
}
}, 0, 40);
}
在游戏中我获得调试:OOC消息返回所以ooc.add(s)应该没问题,但是来自我的监听器的第二条消息总是返回false并且永远不会进入if语句。我认为这可能是由于将Sender强制转换为播放器造成的,这就是为什么我也尝试在字符串数组上执行此操作,并且来自命令和侦听器的调试消息都返回完全相同的播放器名称但是包含始终为false。这里也是String尝试的代码。
public class RpChat implements CommandExecutor, Listener {
private ArrayList<String> ooc = new ArrayList<String>();
private ArrayList<String> ic = new ArrayList<String>();
private ArrayList<String> shout = new ArrayList<String>();
private ArrayList<String> whisper = new ArrayList<String>();
public boolean onCommand(CommandSender cs, org.bukkit.command.Command cmnd, String string, String[] strings) {
Player p = (Player) cs;
String s = p.getName();
if (cmnd.getName().equalsIgnoreCase("ooc")) {
p.sendMessage("Debug: OOC: Plaer Name: "+ s);
if (ic.contains(s))
ic.remove(s);
if (shout.contains(s))
shout.remove(s);
if (whisper.contains(s))
whisper.remove(s);
ooc.add(s);
}
return true;
}
@EventHandler
public void onPlayerChatEvent(AsyncPlayerChatEvent event) {
Player p = event.getPlayer();
String s = p.getName();
Bukkit.getScheduler().scheduleSyncRepeatingTask(Dungeon.getPlugin(), new Runnable() {
public void run() {
if (ooc.contains(s)) {
event.setFormat(ChatColor.RED + "[OOC] " + ChatColor.WHITE + "%s" + ": " + "%s");
p.sendMessage("Debug Player = " + ooc.contains(s)+ " Plaer Name: "+ s);
}
else{
p.sendMessage("Debug Player = " + ooc.contains(s)+ " Plaer Name: "+ s);
}
}
}, 0, 40);
}
请告诉我它的错误导致我已经忘记了,并为我可怜的英语感到抱歉; /
答案 0 :(得分:0)
解决方法非常简单:
将所有ArrayLists保持静态。 EventHandler以不同的方式处理类,每次都创建一个新的类,使得变量声明对事件无用。
private static ArrayList<String> ooc = new ArrayList<String>();
private static ArrayList<String> ic = new ArrayList<String>();
private static ArrayList<String> shout = new ArrayList<String>();
private static ArrayList<String> whisper = new ArrayList<String>();
这样,所有事件处理程序都会使用您的列表,使其成为唯一列表。