java - 从最高到最低排列数字

标签 java minecraft bukkit

我使用文件夹中的每个文件获取 double

if(label.equalsIgnoreCase("baltop")){
        if(!(sender instanceof Player)){
            CommandUtils.invalidCommandSender(sender);
            return true;
        }
        File[] files = new File(ServerCore.getPlugin().getDataFolder(), File.separator + "PlayerData").listFiles();
        for(File file : files){
            FileConfiguration playerData = YamlConfiguration.loadConfiguration(file);
            double bal = playerData.getDouble("Money");
            ChatUtils.sendRawMessage(sender, Bukkit.getOfflinePlayer(UUID.fromString(file.getName().replace(".yml", ""))).getName() + ": " + bal);
        }
        return true;
    }

它按文件顺序显示了所有价格,但我想按余额从最高到最低的顺序排列,如果两个玩家的金额相同会怎样?

最佳答案

您应该首先读取所有内容,并将它们存储在 TreeSet 中,如下所示:

if(label.equalsIgnoreCase("baltop")){
    if(!(sender instanceof Player)){
        CommandUtils.invalidCommandSender(sender);
        return true;
    }
    TreeSet<Balance> set = new TreeSet<>();
    set = set.descendingSet();
    File[] files = new File(ServerCore.getPlugin().getDataFolder(), File.separator + "PlayerData").listFiles();
    for (File file : files){
        FileConfiguration playerData = YamlConfiguration.loadConfiguration(file);
        double bal = playerData.getDouble("Money");
        UUID uuid = UUID.fromString(file.getName().replace(".yml", ""));
        set.add(new Balance( Bukkit.getOfflinePlayer(uuid).getName(), uuid, bal));
    }

    for (Balance b : set) {
        ChatUtils.sendRawMessage(sender, b.name + ": " + b.balance);
    }
    return true;
}

private static class Balance implements Comparable<Balance> {
    public String name;
    public UUID uuid;
    public double balance;
    public Balance(String n, UUID u, double b) {
        name = n;
        uuid = u;
        balance = b;
    }
    @Override
    public int compareTo(Balance b) {
        double d = balance - b.balance;
        if (d<-0.001||d>0.001)
            return (int) Math.signum(d);

        int e = -name.compareToIgnoreCase(b.name);
        if (e != 0)
            return e;
        return -uuid.compareTo(b.uuid);
    }
}

此实现将按余额降序显示余额,并且,如果两个玩家具有相同的余额,则按其姓名的升序显示余额,无论大小写。 UUID 比较只是名称冲突的最后手段,因为我真的不知道 bukkit 是否允许多个玩家的名称仅大小写不同。

关于java - 从最高到最低排列数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336644/

相关文章:

java - org.hibernate.AnnotationException : Use of @OneToMany or @ManyToMany targeting an unmapped class

java - 拆分字符串具有带正则表达式的符号(许多管道)

JavaFX 如何将字符串值设置为 TableView

Java - BungeeCord 关闭

java - Bukkit - 插件未加载 - 主要错误

java - 如何动态改变重复Java Runnable的周期?

java - 为什么这个对象不能被序列化?

Java VRPN 按钮服务器

java - 如何阻止我的配置覆盖新值?

java - 如何获取库存中单击的项目的名称