2015-03-31 55 views
2

我想做一個廣播命令。當/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]); 

但我知道這是錯誤的。我怎樣才能解決這個問題?

回答

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); 
} 
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 
} 
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);