Solved Getting String out of yml file

Discussion in 'Plugin Development' started by wand555, Jun 18, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    wand555

    Hello,
    right now I'm trying to implement a "Ladder" feature, which when shows a ranking of the players with the most amount of money (called with /talon ladder). Now I thought a bit on how to do this. The bank account is all set up and works perfectly fine and creates this in a custom yml file when a player logs in for their first time (or after the file has been deleted manually:
    pic 1.png
    Code (open)

    Code:
        public static void firstLogin(Player player) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            cfg.set(player.getUniqueId().toString() + " .talon", Talon.getTalon(player.getUniqueId()));
            cfg.set(player.getUniqueId().toString() + " .username", player.getName());
            cfg.set(player.getUniqueId().toString() + " .permission", false);
            Talon.plugin.names.add(player.getUniqueId().toString());
            Talon.saveCustomYml(cfg, file);
        }
    Now my way of approaching this problem (without googling) would be, to get the first UUID (and the corresponding talon value), take it, compare it with the second UUID and keep the larger one. Then take the larger one and compare it with the third UUID and store the larger one again. You would keep repeating this process until you went through all UUID's once and have the largerst UUID. Save this UUID as the first object (in an array for example). Now we repeat it again, excluding the UUID we stored in the array.
    While only having loosely thought about this method, I think I have to copy the contents of the yml first, before removing a UUID. Maybe a HashMap with the types UUID and Integer will work?
    But now on to the main problem:
    Before I can even start forming my idea into code, I need to get the UUID from the yml. While I know how to get another string/value (e.g. I get talon with
    Code:
    public static Integer getTalon(UUID uuid) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            int talon = cfg.getInt(uuid.toString() + " .talon");
            return talon;
        }
    ), but I don't know how the get the "heading", so to speak the UUID. I tried using
    Code:
    cfg.getString(player.getUniqueId().toString());
    but even that just returns "null" which I think means, after checking out the bukkit docs, that it can't find the path and therefore tries to return the default section, which I haven't set, so it returnes null (at least getDefaultSection() returns null).
    I figured there are some workarounds like storing every UUID in an extra yml when they login using
    Code:
    cfg.getStringList("UUID's").add(player.getUniqueId().toString());
    , but I'm really sure there's a way to do it directly.
    Furthermore, getName() and getCurrentPath() looked promissing, but both don't quite seem to work how I want to, since they don't return anything (makes sense when they're void). I might just not understand them properly though.
    I also thought about changing how I store values and strings in general, so to speak, to make it like:
    UUID: uuid
    Talon: value
    etc.. , but then I would have to change a lot when calling a user's information, because the path wouldn't be unique anymore.
    I hope somebody might have an idea on how to solve this.
    Entire code incase somebody wants to read it (messy and not really cleaned up):
    Main (open)

    Code:
    package me.wand555.Talon;
    
    import java.io.File;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemFlag;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.permissions.PermissionAttachment;
    import org.bukkit.permissions.PermissionAttachmentInfo;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Talon extends JavaPlugin {
        private TalonCommandExecutor myTalonCommandExecutor;
        public HashMap<UUID, PermissionAttachment> playerPermissions = new HashMap<>();
        //public ArrayList<String> names = new ArrayList<String>();
    
        public static Talon plugin;
    
        public Talon() {
            plugin = this;
        }
    
    
    
        @Override
        public void onEnable() {
            super.onEnable();
            myTalonCommandExecutor = new TalonCommandExecutor(this);
            getCommand("talon").setExecutor(myTalonCommandExecutor);
            new TalonCraftEvent(this);
            new TalonPermsEvent(this);
            this.getConfig().options().copyDefaults(true);
            this.saveConfig();
        }
        @Override
        public void onDisable() {
            playerPermissions.clear();
            super.onDisable();
     
        }
    
    
        public static void firstLogin(Player player) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            cfg.set(player.getUniqueId().toString() + " .talon", Talon.getTalon(player.getUniqueId()));
            cfg.set(player.getUniqueId().toString() + " .username", player.getName());
            cfg.set(player.getUniqueId().toString() + " .permission", false);
            Talon.saveCustomYml(cfg, file);
        }
    
    
        public static void setUpPermission(Player player) {
            PermissionAttachment attachment = player.addAttachment(plugin);
            plugin.playerPermissions.put(player.getUniqueId(), attachment);
     
            for(String groups : plugin.getConfig().getConfigurationSection("Groups").getKeys(false)) { //loop through all groups
                for(String permissions : plugin.getConfig().getStringList("Groups." + groups + ".permissions")) { //get permissions
                    attachment.setPermission(permissions, true);
                }
            }
            Talon.addPerm(player.getUniqueId());
        }
    
        public static void removePermission(Player player, String permission) {
            for (PermissionAttachmentInfo paInfo : player.getEffectivePermissions()) {
                if (paInfo.getAttachment() != null && paInfo.getAttachment().getPlugin().equals(plugin)) {
                    paInfo.getAttachment().unsetPermission(permission);
                }
            }
            Talon.deletePerm(player.getUniqueId());
        }
    
        public static boolean isInteger(String s) {
            return isInteger(s,8);
        }
    
        public static boolean isInteger(String s, int radix) {
            if(s.isEmpty()) return false;
            for(int i = 0; i < s.length(); i++) {
                if(i == 0 && s.charAt(i) == '-') {
                    if(s.length() == 1) return false;
                    else continue;
                }
                if(Character.digit(s.charAt(i),radix) < 0) return false;
            }
            return true;
        }
    
        public static void checkOrdner() {
            File file = new File("plugins//Talon");
            if(!(file.exists())) {
                file.mkdir();
            }
        }
    
        public static void saveCustomYml(FileConfiguration ymlConfig, File ymlFile) {
            try {
            ymlConfig.save(ymlFile);
            } catch (IOException e) {
            e.printStackTrace();
            }
        }
    
        public static Integer getTalon(UUID uuid) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            int talon = cfg.getInt(uuid.toString() + " .talon");
            return talon;
        }
    
    
        public static void addTalon(UUID uuid, String name, int amount) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            int talon = cfg.getInt(uuid.toString() + " .talon");
            talon = amount + talon;
            cfg.set(uuid.toString() + " .talon", talon);
            cfg.set(uuid.toString() + " .username", name);
            Talon.saveCustomYml(cfg, file);
        }
    
        public static boolean removeTalon(UUID uuid, String name, int amount) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            int talon = cfg.getInt(uuid.toString() + " .talon");
            if((talon - amount) >= 0) {
                talon = talon - amount;
                cfg.set(uuid.toString() + " .talon", talon);
                cfg.set(uuid.toString() + " .username", name);
                Talon.saveCustomYml(cfg, file);
                return true;
            }
            else {
                return false;
            }
        }
    
        public static void addPerm(UUID uuid) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            cfg.set(uuid.toString() + " .permission", true);
            Talon.saveCustomYml(cfg, file);
        }
    
        public static void deletePerm(UUID uuid) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            cfg.set(uuid.toString() + " .permission", false);
            Talon.saveCustomYml(cfg, file);
        }
    
        public static boolean hasPerm(UUID uuid) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            return(cfg.getBoolean(uuid.toString() + " .permission"));
        }
    
        public static void InvtoBankTalon(UUID uuid, String name, int amount, Inventory inv) {
            Player player = Bukkit.getPlayer(uuid);
     
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
     
            if(inv.containsAtLeast(Talon.physicalCurrencyCreator(uuid), amount) == true) {
                int talon = cfg.getInt(uuid.toString() + " .talon");
                //int talon_vorher = talon;
                talon = talon + amount;
                cfg.set(uuid.toString() + " .talon", talon);
                cfg.set(uuid.toString() + " .username", name);
                Talon.saveCustomYml(cfg, file);
                for(int i=0; i<amount; i++) {
                    inv.removeItem(Talon.physicalCurrencyCreator(uuid));
                }
                player.sendMessage("Erfolgreich " + amount + " Talon transferiert.");
                player.sendMessage("Du hast nun " + talon + " Talon auf deinem Konto.");
            }
            else {
                player.sendMessage("Nicht genügend Talon im Inventar.");
            }
        }
    
        public static void BanktoInvTalon(UUID uuid, String name, int amount, Inventory inv) {
            Player player = Bukkit.getPlayer(uuid);
     
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            if(inv.firstEmpty() == -1 ) {
                if(!(inv.containsAtLeast(Talon.physicalCurrencyCreator(uuid), 1))) {
                    player.sendMessage("Kein Platz im Inventar.");
                }
                else {
                    int talon = cfg.getInt(uuid.toString() + " .talon");
                    if(talon >= amount) {
                        for(int i=0; i<amount; i++) {
                            inv.addItem(Talon.physicalCurrencyCreator(uuid));
                            talon--;
                            cfg.set(uuid.toString() + " .talon", talon);
                            cfg.set(uuid.toString() + " .username", name);
                            Talon.saveCustomYml(cfg, file);
                        }
                    }
                    else {
                        player.sendMessage("Du hast nur " + talon + " Talon auf deinem Konto.");
                    }
                }
         
            }
            else {
                int talon = cfg.getInt(uuid.toString() + " .talon");
                if(talon >= amount) {
                    for(int i=0; i<amount; i++) {
                        inv.addItem(Talon.physicalCurrencyCreator(uuid));
                        talon--;
                        cfg.set(uuid.toString() + " .talon", talon);
                        cfg.set(uuid.toString() + " .username", name);
                        Talon.saveCustomYml(cfg, file);
                    }
                }
                else {
                    player.sendMessage("Du hast nur " + talon + " Talon auf deinem Konto.");
                }
            }
        }
    
        public static ItemStack physicalCurrencyCreator(UUID uuid) {
            ItemStack diamond = new ItemStack(Material.DIAMOND, 1);
            ItemMeta meta = diamond.getItemMeta();
            meta.setDisplayName("Talon");
            ArrayList<String> itemdesc = new ArrayList<String>();
            itemdesc.add("Physikalische Währung");
            meta.setLore(itemdesc);
            meta.addEnchant(Enchantment.DURABILITY, 1, true);
            meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
     
            diamond.setItemMeta(meta);
     
            return(diamond);
        }
    
    
        public static void Ladder(Player player) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
            String player1_string = cfg.getString(player.getUniqueId().toString());
     
     
     
            //java.util.List<java.util.Map.Entry<String,Integer>> pairList = new java.util.ArrayList<>(); //Create Map with String and Integer type
     
     
            //java.util.Map.Entry<String,Integer> pair1 = new java.util.AbstractMap.SimpleEntry<>("Not Unique key1",1);
     
            // List<?> names =  cfg.getList(player.getUniqueId().toString());
            ArrayList<String> names = new ArrayList<String>();
            names.add(cfg.getString(player.getUniqueId().toString()));
            //cfg.getStringList(player.getUniqueId().toString()).add(player.getUniqueId().toString());
            //List<String> names = cfg.getStringList(player.getUniqueId().toString());
            System.out.println(cfg.getString(player.getUniqueId().toString()));
            System.out.println(cfg.getDefaultSection());
            System.out.println(cfg.getCurrentPath());
            for(int i=0; i<names.size(); i++) {
                System.out.println(names.get(i));
            }
     
        }
    
        public static String compare(UUID uuid1, UUID uuid2) {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
     
            int talon1 = cfg.getInt(uuid1.toString() + " .talon");
            int talon2 = cfg.getInt(uuid2.toString() + " .talon");
            if(talon1 > talon2) {
                return uuid1.toString();
            }
            else if(talon1 < talon2) {
                return uuid2.toString();
            }
     
            //Player player1 = Bukkit.getPlayer(uuid1);
            //Player player2 = Bukkit.getPlayer(uuid2);
     
            return null;
        }
    }
    

    CommandExecutor (open)

    Code:
    package me.wand555.Talon;
    
    import org.bukkit.Bukkit;
    
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    public class TalonCommandExecutor implements CommandExecutor {
        private Talon plugin;
    
        public TalonCommandExecutor(Talon plugin) {
            this.plugin = plugin;
        }
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            Player player = null;
            if(sender instanceof Player) {
                player = (Player) sender;
            }
            if(cmd.getName().equalsIgnoreCase("talon")) {
                if(!(player==null)) {
                    if(args.length == 0) { 
                        player.sendMessage("Du hast aktuell " + Talon.getTalon(player.getUniqueId()) + " Talon.");
                    }
                    /*
                    else if(args.length == 1) {
                        String target = args[0];
                        Player target_player = Bukkit.getServer().getPlayer(args[0]);
                        if(player == target_player) {
                            player.sendMessage("Deine eigene Talon kannst du mit /talon aufrufen.");
                        }
                        else {
                            player.sendMessage(target + " hat " + Talon.getTalon(target_player.getUniqueId()) + " Talon.");
                        }
                 
                    }*/
                    else if(args.length == 1 && args[0].equalsIgnoreCase("ladder")) {
                        Talon.Ladder(player);
                    }
                    else if(args.length == 2 && args[0].equalsIgnoreCase("sell")) {
                        Talon.InvtoBankTalon(player.getUniqueId(), player.getName(), Integer.valueOf(args[1]), player.getInventory());
                    }
                    else if(args.length == 2 && args[0].equalsIgnoreCase("buy")) {
                        Talon.BanktoInvTalon(player.getUniqueId(), player.getName(), Integer.valueOf(args[1]), player.getInventory());
                    }
             
             
                    else if(args.length == 3 && args[0].equalsIgnoreCase("give") && Talon.isInteger(args[2]) == true) {
                        if(player.hasPermission("talon.admin") || player.isOp() == true) {
                            String target = args[1];
                            Player target_player = Bukkit.getServer().getPlayer(args[1]);
                     
                            Talon.addTalon(target_player.getUniqueId(), target_player.getName(), Integer.valueOf(args[2]));
                            if(player == target_player) {
                                player.sendMessage("Du hast dir selber " + Integer.valueOf(args[2]) + " Talon hinzugefügt.");
                            }
                            else {
                                player.sendMessage(target + " wurde " + Integer.valueOf(args[2]) + " Talon hinzugefügt.");
                                target_player.sendMessage(player.getName() + " hat dir " + Integer.valueOf(args[2]) + " Talon hinzugefügt.");
                            }
                        }
                        else {
                            player.sendMessage("Du hast dafür keine Berechtigung.");
                        }
                 
                 
                    }
                    else if(args.length == 3 && args[0].equalsIgnoreCase("take") && Talon.isInteger(args[2]) == true) {
                        if(player.hasPermission("talon.admin") || player.isOp() == true) {
                            String target = args[1];
                            Player target_player = Bukkit.getServer().getPlayer(args[1]);
                     
                            if(Talon.removeTalon(target_player.getUniqueId(), target_player.getName(), Integer.valueOf(args[2])) == true) {
                                if(player == target_player) {
                                    player.sendMessage("Du hast dir selber " + Integer.valueOf(args[2]) + " Talon abgezogen.");
                                }
                                else {
                                    player.sendMessage(target + " wurde " + Integer.valueOf(args[2]) + " Talon abgezogen.");
                                    target_player.sendMessage(player.getName() + " hat dir " + Integer.valueOf(args[2]) + " Talon abgezogen.");
                                }
                            }
                            else {
                                player.sendMessage(target_player.getName() + " besitzt nur " + Talon.getTalon(target_player.getUniqueId()) + " Talon.");
                            }
                     
                     
                        }
                        else {
                            player.sendMessage("Du hast dafür keine Berechtigung.");
                        }
                 
                 
                    }
                    else if(args.length == 3 && args[0].equalsIgnoreCase("give") && args[1].equalsIgnoreCase("permission")) {
                        if(player.isOp() == true) {
                            String target = args[2];
                            Player target_player = Bukkit.getServer().getPlayer(args[2]);
                            if(target_player.hasPermission("talon.admin")) {
                                player.sendMessage(target + " hat bereits die Berechtigung.");
                            }
                            else {
                                Talon.setUpPermission(target_player);
                                if(player == target_player) {
                                    player.sendMessage("Du hast dir die Berechtigung gegeben.");
                                }
                                else {
                                    player.sendMessage("Du hast " + target + " die Berechtigung gegeben.");
                                    target_player.sendMessage(player.getName() + " hat dir die Berechtigung gegeben.");
                                }
                            }
                        }
                        else  {
                            player.sendMessage("Du musst OP haben, um diesen Befehl auszuführen.");
                        }
                    }
                    else if(args.length == 3 && args[0].equalsIgnoreCase("remove") && args[1].equalsIgnoreCase("permission")) {
                        if(player.isOp() == true) {
                            String target = args[2];
                            Player target_player = Bukkit.getServer().getPlayer(args[2]);
                            if(target_player.hasPermission("talon.admin")) {
                                //plugin.playerPermissions.remove(target_player.getUniqueId());
                                Talon.removePermission(target_player, "talon.admin");
                                if(player == target_player) {
                                    player.sendMessage("Du hast dir die Berechtigung entzogen.");
                                }
                                else {
                                    player.sendMessage("Du hast " + target + " die Berechtigung entzogen.");
                                    target_player.sendMessage(player.getName() + " hat dir die Berechtigung entzogen.");
                                }
                            }
                            else {
                                    player.sendMessage(target + " hat bereits keine Berechtigung.");
                         
                            }
                        }
                        else {
                            player.sendMessage("Du musst OP haben, um diesen Befehl auszuführen.");
                        }
                     
                    }
             
                }
            }
     
            return true;
        }
    }
    

    Registering when new player logs in (open)

    Code:
    package me.wand555.Talon;
    
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerQuitEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class TalonPermsEvent implements Listener {
        public TalonPermsEvent(JavaPlugin plugin) {
            plugin.getServer().getPluginManager().registerEvents(this, plugin);
        }
    
        @EventHandler
        public void login(PlayerJoinEvent event) {
            if(Talon.hasPerm(event.getPlayer().getUniqueId()) == true) {
                Talon.setUpPermission(event.getPlayer());
            }
            else {
                Talon.firstLogin(event.getPlayer());
            }
        }
    
        @EventHandler
        public void logout(PlayerQuitEvent event) {
            Talon.plugin.playerPermissions.remove(event.getPlayer().getUniqueId());
        }
    }
    

    plugin.yml (open)

    Code:
    name: Talon
    main: me.wand555.Talon.Talon
    version: 1.1.2
    description: >
                 Creates a Talon currency system.
    author: wand555
    commands:
      talon:
        usage: /talon
        description: Shows players account balance.
      talon:
        usage: /talon <player>
        description: Shows the selected players account balance.
      give:
        usage: /talon give <player> <amount>
        description: Gives a player a certain amount of Talon.
      take:
        usage: /talon take <player> <amount>
        description: Takes away a certain amount of Talon from a player.
      buy:
        usage: /talon buy <amount>
        description: Transfers a certain amount of Talon from the bank account into the inventory.
      sell:
        usage: /talon sell <amount>
        description: Transfers a certain amount of Talon from the inventory into the bank account.
      give:
        usage: /talon give permission <player>
        description: Gives a player the permission "-talon.admin"
      remove:
        usage: /talon remove permission <player>
        description: Removes the permission "-talon.admin" from a player
    
        
     
  2. Online

    KarimAKL

    @wand555
    1. Instead of using "//" in a file path, use "File.separator" or you can just use the "getDataFolder()" method from your main class to get your plugin's folder.
    2. You can get all the keys in a config using this:
    Code:Java
    1. File file = /*your file*/;
    2. FileConfiguration config = YamlConfiguration.loadConfiguration(file);
    3. Set<String> keys = config.getKeys(false);
    4. // The key in this example would be the UUID of the players returned as a string
    5. for (String key : keys) {
    6. // Do something with the uuid here
    7. }

    3. I use something like this to get the top X of anything:
    Code:Java
    1. // Create a method to get the top players
    2. // 'max' is the amount of players we want to get
    3. // if it's possible (the amount of players could be less than specified)
    4. public UUID[] getTopPlayers(int max) {
    5. // Create a map with the players and their talon
    6. // Or get your map if you have it somewhere else
    7. Map<UUID, Integer> players = new HashMap<>();
    8. // Add all your players and values using the above method of getting keys
    9. // Create a list and fill it with the map's entries
    10. List<Entry<UUID, Integer>> entries = new ArrayList<>(players.entrySet());
    11. // Sort the list by the values
    12. Collections.sort(entries, new Comparator<Entry<UUID, Integer>>() {
    13. public int compare(Entry<UUID, Integer> entry1, Entry<UUID, Integer> entry2) {
    14. return entry1.getValue().compareTo(entry2.getValue());
    15. }
    16. // Reverse the list to get the highest value first
    17. }.reversed());
    18. // Create the array of UUIDs we want to return
    19. // We set the maximum amount of UUIDs we want to get as well
    20. UUID[] player = new UUID[max];
    21. for (int j = 0; j < max; j++) {
    22. try {
    23. // Set the UUID in the array
    24. player[j] = entries.get(j).getKey();
    25. // We catch an IndexOutOfBoundsException in case of
    26. // the 'max' being higher than the amount of players
    27. // Break out of the loop in case that happens
    28. break;
    29. }
    30. }
    31. // Return the UUIDs of the top 'max' players
    32. return player;
    33. }

    This code can be edited to get the value along with the UUID if you want.
     
  3. Offline

    wand555

    Hey @KarimAKL and thanks for the detailed explanation.
    So far I've tried to implement the first half of the code you sent, however I struggle a bit with converting the string to UUID. Usually it worked when I wrote
    Code:
    UUID.fromString(UUID_String);
    but now when I type
    Code:
    for(String key : keys) {
    players.put(UUID.fromString(key), Talon.getTalon(UUID.fromString(key)));
    }
    it throws a NumberFormatException at that line, which confuses me, since that would mean that the programm cannot convert the string into an UUID.
    error.png
    "bde2320283c6" is the last part of the entered UUID.
    And after looking in the javadocs for UUID, the fromString method can throw an IllegalArgumentException, which includes NumberFormatException, when it doesn't "fit" (I don't really understand how it is defined in toString).
    tl;dr I have no clue why the error occures and how to fix it.
     
  4. Online

    KarimAKL

    Where do you see the method throws a NumberFormatException? I only see that it throws an IllegalArgumentException.
    Are you sure 'UUID.fromString(key)' is throwing that exception?
     
  5. Offline

    wand555

    Yeah you're right, misread the docs.
    Honestly I have no clue, but I assume it does.
    Error (open)
    Screenshot_1.png

    Because if I simplify it to just
    Code:
    UUID uuid2 = UUID.fromString(key);
    it throws the same exception (this is in line 289), while
    Code:
    UUID uuid2 = UUID.fromString("c41c9dcf-20cb-406d-aacd-bde2320283c6");
    or
    Code:
    UUID uuid2 = UUID.fromString(player.getUniqueID().toString());
    work (I know the last example is useless, but you get the point)
    The error in the commandExecutor at line 40 is just the method being called Talon.Ladder()
     
    Last edited: Jun 19, 2019
  6. Online

    KarimAKL

    @wand555 Ah, my bad. The UUID#fromString calls Long#decode which then throws a NumberFormatException.
    Try printing the key to the console without using UUID#fromString. You can just comment that out for now.
    Try showing us the file you are trying to get as well.
     
  7. Offline

    wand555

    @KarimAKL
    works perfectly fine and prints out the UUID as a string.

    Not quite sure what you mean with that, but I have created a Talon.yml where the users UUID is stored. And to add a player to the HashMap for e.g., I try to get the player by converting the String in Talon.yml to a UUID and then to the player with getOfflinePlayer.
     
  8. Online

    KarimAKL

    And you are sure that there's no spaces that you can't see because there's no text after it?
    Example:
    'c41c9dcf-20cb-406d-aacd-bde2320283c6 '
    There's a space after that string.
    I'm not sure if the string is trimmed before trying to turn it into a UUID. :7
    Yeah, i meant showing us the file layout.
     
  9. Offline

    wand555

    Thank you, I didn't think about that.
    Code:
    System.out.println(UUID.fromString(key.trim())); 
    and
    Code:
    players.put(UUID.fromString(key.trim()), Talon.getTalon(UUID.fromString(key.trim())));
    both work now.
    Tomorrow I'll try to do the stuff you included in your first reply.

    EDIT next day:
    @KarimAKL
    Everything works now as intended.
    Though I only use one method to store the players
    Ladder (open)

    Code:
    public static UUID[] Ladder() {
            Talon.checkOrdner();
            File file = new File("plugins//Talon", "talon.yml");
            FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
    
            Set<String> keys = cfg.getKeys(false);
            Map<UUID, Integer> players = new HashMap<>();
    
            for(String key : keys) {
                players.put(UUID.fromString(key.trim()), Talon.getTalon(UUID.fromString(key.trim())));
            } 
         
            List<Entry<UUID, Integer>> entries = new ArrayList<>(players.entrySet());
         
            Collections.sort(entries, new Comparator<Entry<UUID, Integer>>() {
                public int compare(Entry<UUID, Integer> entry1, Entry<UUID, Integer> entry2) {
                    return entry1.getValue().compareTo(entry2.getValue());
                }
            }.reversed());
         
            UUID[] uuid = new UUID[Talon.LadderSize(keys)];
         
            for(int i=0; i<uuid.length; i++) {
                try {
                    uuid[i] = entries.get(i).getKey();
                }
                catch (IndexOutOfBoundsException e) {
                    break;
                }
            }
            return uuid;
        }
    and call this method when a player executes /talon ladder
    Command (open)

    Code:
    else if(args.length == 1 && args[0].equalsIgnoreCase("ladder")) {
                        player.sendMessage("Talon Ranking");
                        for(int i=0; i<Talon.Ladder().length; i++) {
                            player.sendMessage((i+1) + ". " + Bukkit.getOfflinePlayer(Talon.Ladder()[i]).getName() + " hat " + Talon.getTalon(Talon.Ladder()[i]) + " Talon");
                        }
                    }

    Now this might sound a bit nitpicky, but is there a way to get whether multiple players have the same amount of Talon?
    I tried looking into your Collections.sort class, where I found that compareTo returns 0 when both values are equal, but I don't really know how to use this information properly.
     
    Last edited: Jun 20, 2019
    KarimAKL likes this.
  10. Online

    KarimAKL

    What do you want to do with that information?
     
  11. Offline

    wand555

    If for example 1st and 2nd are tied, both should have the 1st as number and the third one should have 3rd, so basically skipping 2nd place since there are two 1st places.
     
  12. Online

    KarimAKL

    @wand555 That would require changing the code i posted a bit because it only returns the players, not their value. I haven't tried this before but i'm thinking it would be possible to return the players as player/value pair (in a map) and then when you want to display it, you simply check if the current player's value is the same as the previous player's value and if so, give them the same rank as the previous one.
    Hope that made sense.
     
  13. Offline

    wand555

    But when do I store the value from compareTo?
    If I do it within the compare method the values and their corresponding UUID are not sorted. And I can't call it later because your version is written with an anonymous inner class (right?).
     
  14. Online

    KarimAKL

    @wand555 The values are in the list of entries.
    What i meant with my previous post was that you could probably do something like this:
    Code:Java
    1. // Assuming we change the return type of 'getTopPlayers'
    2. List<Entry<UUID, Integer>> top10 = getTopPlayers(10);
    3. // We store the players and their placement in 'placements'
    4. Map<UUID, Integer> placements = new HashMap<>();
    5. // Looping the players
    6. for (int j = 0; j < top10.size(); j++) {
    7. // Get the current player in the loop
    8. Entry<UUID, Integer> entry1 = top10.get(j);
    9. // Check if this is the first player
    10. if (j == 0) {
    11. // If so, we put them at first place
    12. placements.put(entry1.getKey(), 1);
    13. // And continue the loop
    14. continue;
    15. }
    16. // If not, we get the previous player in the loop
    17. Entry<UUID, Integer> entry2 = top10.get(j - 1);
    18. // We then check if the current player has the same value as the previous one
    19. if (entry1.getValue() == entry2.getValue()) {
    20. // If so, we set the current player's placement to the same as the previous player's placement
    21. placements.put(entry1.getKey(), placements.get(entry2.getKey()));
    22. continue;
    23. }
    24. // If not, we set their placement to the current loop index (+1 to go from 1-10 instead of 0-9)
    25. placements.put(entry1.getKey(), j + 1);
    26. }
    27. // In this example, 'ranks' will contain '1="1st"', "2="2nd"" etc.
    28. Map<Integer, String> ranks = new HashMap<>();
    29. // We then loop the placements we got
    30. for (Entry<UUID, Integer> entry : placements.entrySet()) {
    31. // Get the player
    32. Player player = Bukkit.getPlayer(entry.getKey());
    33. // Get their rank
    34. String placement = ranks.get(entry.getValue());
    35. // Print out the player's name and their placement
    36. System.out.println(player.getName()+": "+placement);
    37. }

    I wrote this in the post so it might not be correct, but it might give you an idea of how to do this.
     
  15. Offline

    wand555

    Added/changed your code but the the same problem remains. the Map "entries" is sorted and contains the UUID and, different from what you said, the amount of Talon the UUID has.
    Code:
    System.out.println(entries.get(j).getKey() + " " + entries.get(j).getValue()); 
    Looks like:
    1.png
    When I create another map and do everything you wrote on it
    Code:
    System.out.println(uuid.getKey() + " " + uuid.getValue());
    looks like:
    2.png
    which makes sense. c41... should be 1st and c84... should be 2nd. But as you can probably already tell, it is sorted the wrong order and therefore doesn't function properly with

    Code:
    for(Entry<UUID, Integer> entry : Talon.inbetween(Talon.Ladder()).entrySet()) {
                            player.sendMessage(ranks.get(entry.getValue()) + " " + Bukkit.getOfflinePlayer(entry.getKey()).getName() + " hat " + Talon.getTalon(entry.getKey()) + " Talon!");
                        }
    and looks like:
    3.png
     
  16. Online

    KarimAKL

    @wand555 A HashMap is not sorted. Try using List<Entry<K,V>> instead.
     
  17. Offline

    wand555

    Alright, pretty sure it's working now.
    I've never worked with maps nor Abstract Maps before though.
    Sort players by their Talon (with their UUID):
    Code:java
    1. public static List<Entry<UUID, Integer>> Ladder() {
    2. Talon.checkOrdner();
    3. File file = new File("plugins//Talon", "talon.yml");
    4. FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
    5.  
    6. Set<String> keys = cfg.getKeys(false);
    7. Map<UUID, Integer> players = new HashMap<>();
    8.  
    9. for(String key : keys) {
    10. players.put(UUID.fromString(key.trim()), Talon.getTalon(UUID.fromString(key.trim())));
    11. }
    12.  
    13. List<Entry<UUID, Integer>> entries = new ArrayList<>(players.entrySet()); //in "entries" sind UUID und Talon gespeichert
    14.  
    15.  
    16. Collections.sort(entries, new Comparator<Entry<UUID, Integer>>() {
    17. public int compare(Entry<UUID, Integer> entry1, Entry<UUID, Integer> entry2) {
    18.  
    19. return entry1.getValue().compareTo(entry2.getValue());
    20. }
    21. }.reversed());
    22. return entries;
    23. }


    with Tiebreaker:

    Code:java
    1. @SuppressWarnings("rawtypes")
    2. public static List<Entry<UUID, Integer>> inbetween(List<Entry<UUID, Integer>> entries) {
    3. List<Entry<UUID, Integer>> placements = new ArrayList<Map.Entry<UUID, Integer>>(); //UUID und compareTo value
    4.  
    5. for(int j=0; j<entries.size(); j++) {
    6. Entry<UUID, Integer> entry1 = entries.get(j);
    7. if(j == 0) {
    8. placements.add(j, new AbstractMap.SimpleEntry(Talon.Ladder().get(j).getKey(), new Integer(1)));
    9.  
    10. continue;
    11. }
    12. Entry<UUID, Integer> entry2 = entries.get(j - 1);
    13. if(entry1.getValue() == entry2.getValue()) {
    14. placements.add(j, new AbstractMap.SimpleEntry(entry1.getKey(), placements.get(j-1).getValue()));
    15. continue;
    16. }
    17. placements.add(j, new AbstractMap.SimpleEntry(entry1.getKey(), new Integer(j+1)));
    18. }
    19. return placements;
    20. }


    Call it when command executed:

    Code:java
    1. else if(args.length == 1 && args[0].equalsIgnoreCase("ladder")) {
    2. player.sendMessage(ChatColor.GOLD + " Talon Ranking");
    3. Map<Integer, String> ranks = new HashMap<>();
    4. ranks.put(1, "1.");
    5. ranks.put(2, "2.");
    6. ranks.put(3, "3.");
    7. Talon.inbetween(Talon.Ladder());
    8.  
    9. for(int i=0; i<Talon.inbetween(Talon.Ladder()).size(); i++) {
    10. player.sendMessage(ranks.get(Talon.inbetween(Talon.Ladder()).get(i).getValue()) + " " + Bukkit.getOfflinePlayer(Talon.inbetween(Talon.Ladder()).get(i).getKey()).getName() + " hat " + Talon.getTalon(Talon.inbetween(Talon.Ladder()).get(i).getKey()) + " Talon!");
    11. }
    12. }


    Thanks for helping @KarimAKL !
    EDIT: HA, finally found how to write in fancy java code
     
  18. Online

    KarimAKL

Thread Status:
Not open for further replies.

Share This Page