我想发一个广播命令。当/broadcast This is a test
运行时,它会在游戏中广播这是一个测试(带空格)。我尝试过使用:
Bukkit.getServer().broadcastMessage(ChatColor.RED + args[0] + " " + args[1] + " " + args[2] + " " + args[3] + " " + args[4] + " " + args[5] + " " + args[6] + " " + args[7] + " " + args[8] + " " + args[9] + " " + args[10] + " " + args[11] + " " + args[12] + " " + args[13] + " " + args[14]);
但我知道这是错的。我该如何解决这个问题?
答案 0 :(得分:3)
如果您使用的是Java 8,则可以使用Collectors
方便的方法:
Bukkit.getServer().broadcastMessage(
ChatColor.RED + Arrays.stream(args)
.collect(Collectors.joining(" "))
);
否则,遍历数组并使用StringBuilder
连接元素:
if (args.length == 0)
// Premature return instead of using if-else
// to reduce cyclomatic complexity.
return false;
if (args.length == 1) {
// fast path
Bukkit.getServer().broadcastMessage(ChatColor.RED + args[0]);
return false;
}
StringBuilder message = new StringBuilder(args[0]);
for (String each : args)
message.append(" ").append(each);
String broadcast = message.deleteCharAt(0).toString();
Bukkit.getServer().broadcastMessage(ChatColor.RED + broadcast);
答案 1 :(得分:2)
使用
Bukkit.getServer().broadcastMessage(ChatColor.RED + args[0] + " " + args[1] + " " + args[2] + " " + args[3] + " " + args[4] + " " + args[5] + " " + args[6] + " " + args[7] + " " + args[8] + " " + args[9] + " " + args[10] + " " + args[11] + " " + args[12] + " " + args[13] + " " + args[14]);
只有恰好有15个参数才会起作用。如果参数较少,它将抛出ArrayIndexOutOfBoundsException
,因为您试图访问不存在的数组的一部分。如果有更多参数,代码将只打印前15个参数,其余参数将被忽略。
要解决此问题,您需要遍历所有参数:
for(String argument : args)
然后,您需要将参数与空格一起添加到广播消息中:
message+=argument;
message+=" ";
为避免ArrayIndexOutOfBoundsException
,您还应检查是否至少有一个参数:
if(args.length >= 1)
所以,这就是你的代码的样子:
if (args.length >= 1) { // make sure there is at least 1 argument to avoid an ArrayOutOfBoundsException
String message = ""; // initialize the "message" variable
for (String argument : args) { // loop through all of the arguments
message += argument; // add the argument to the message
message += " "; // add a space to the message
}
Bukkit.getServer().broadcastMessage(ChatColor.RED + message); // broadcast the message
}
答案 2 :(得分:1)
以下是最终工作的代码:
if (args.length > 0) {
String broadcast = "";
for (String message : args) {
broadcast = (broadcast + message + " ");
}
Bukkit.getServer().broadcastMessage(ChatColor.WHITE + "[" + ChatColor.GOLD + "BROADCAST" + ChatColor.WHITE + "]" + ChatColor.RED + broadcast);
}