收集特定的论点

时间:2020-08-16 11:43:38

标签: java arrays bukkit collectors

我正在用Java开发游戏插件,无法解决。我想收集args[1]之后的所有内容。这是一些代码,以便您可以更好地理解。

    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if(sender instanceof Player) {
        Player player = (Player) sender;
        if(player.hasPermission("essentials.allow.kick")) {
            if(args.length == 0) {
                player.sendMessage(ChatColor.RED + "Please specify player name.");
            }
            if(args.length == 1) {
                Player target = Bukkit.getPlayer(args[0]);
                if(!target.isValid()) {
                    player.sendMessage(ChatColor.RED + "That player is not on server!");
                }else {
                    target.kickPlayer(ChatColor.RED + "The kick reason has been told!");
                }
            }
            if(args.length > 1) {
                Player target = Bukkit.getPlayer(args[0]);
                if(!target.isValid()) {
                    player.sendMessage(ChatColor.RED + "That player is not on server!");
                }
                else {
                    String message = Stream.of(args).skip(2).collect(Collectors.toList()).toString();
                    target.kickPlayer(ChatColor.RED + message);
                }
            }
        }
    }
    return true;
}

它仅输出[]

1 个答案:

答案 0 :(得分:0)

为了收集第n个元素之后的数组的所有元素,可以使用subList(int fromIndex, int toIndex)类的ArrayList函数。该文档说:

返回此列表中指定的fromIndex(包括)和toIndex(不包括)之间的视图。

因此,您需要将数组转换为List,然后在其上调用函数subList

List<String> list = Arrays.asList(args).sublist(1, args.length);
// Replace number 1 with the start index where you want to trim. (Inclusive)

现在,如果要将列表转换为字符串,可以使用以下功能:

public String buildMessage(List<String> list, String separator) {
    StringBuilder sb = new StringBuilder();
    for (String s: list) {
        sb.append(s).append(separator);
    }
    return sb.toString();
} 

然后通过以下操作调用它:

String message = buildMessage(list, " "); // It will separate the arguments with spaces.

完整演示

String[] args = new String[]{"Hi!", "I", "am", "a", "demo"};
List<String> list = Arrays.asList(args).sublist(1, args.length);
String message = buildMessage(list, " ");
System.out.println("Message: " + message);

产生的输出:

Message: I am a demo 

让我知道这是否适合您!

编辑

@Holger的评论中所述,您可以将完整的演示简化为:

完整演示

String[] args = new String[]{"Hi!", "I", "am", "a", "demo"};
List<String> list = Arrays.asList(args).sublist(1, args.length);
String message = String.join(" ", list);
System.out.println("Message: " + message);

然后,您将不需要buildMessage方法。