Solved [1.13] Error while showing tokenamount to player

Discussion in 'Spigot Plugin Development' started by TheGameKing77, Jul 25, 2018.

  1. Hi,

    I have a problem. I'm simply not good at understanding console errors, sorry bout that.
    I have a command: /tokens, which will display the amount of tokens a player has. The code for displaying the amount is as following:
    Code (Text):
    try {
                           
                            userData.load(userDataFile);
                            config.load(configFile);
                            messages.load(messagesFile);
                           
                            int amount = userData.getInt("user." + p.getUniqueId().toString() + ".tokenAmount");
                            String pname = p.getName();
                            String puuid = p.getUniqueId().toString();
                            String amountString = Integer.toString(amount);
                           
                            p.sendMessage(prefix + ChatColor.translateAlternateColorCodes('&', messages.getString("currentAmount").replace("%player_name%", pname).replace("%player_uuid%", puuid).replace("%amount%", amountString)));
                           
                        } catch(Exception ex) {
                            ex.printStackTrace();
                        }
    And the error i get:
    [21:58:45 WARN]: java.lang.ArrayIndexOutOfBoundsException: 0

    [21:58:45 WARN]: at me.MattieOfficial.UltimateServerTokens.commands.Tokens.onCommand(Tokens.java:48)

    [21:58:45 WARN]: at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)

    [21:58:45 WARN]: at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141)

    [21:58:45 WARN]: at org.bukkit.craftbukkit.v1_13_R1.CraftServer.dispatchCommand(CraftServer.java:692)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.PlayerConnection.handleCommand(PlayerConnection.java:1634)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.PlayerConnection.a(PlayerConnection.java:1469)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.PacketPlayInChat.a(PacketPlayInChat.java:45)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.PacketPlayInChat.a(PacketPlayInChat.java:1)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.PlayerConnectionUtils.a(SourceFile:10)

    [21:58:45 WARN]: at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)

    [21:58:45 WARN]: at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.SystemUtils.a(SourceFile:198)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.MinecraftServer.w(MinecraftServer.java:884)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.DedicatedServer.w(DedicatedServer.java:411)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.MinecraftServer.v(MinecraftServer.java:819)

    [21:58:45 WARN]: at net.minecraft.server.v1_13_R1.MinecraftServer.run(MinecraftServer.java:717)

    [21:58:45 WARN]: at java.base/java.lang.Thread.run(Thread.java:844)

    >

    Anyone able to help me?
     
  2. Please show us what code is in line 48 of the Tokens class. Maybe upload the entire class.
     
  3. Don't use try catch if you don't know what you're catching. Wrapping chunks of erroring code in a try catch statement often does more harm than good.
     
    • Agree Agree x 1
  4. As far as i know i have to use try and catch for loading up the files?

    My whole class:
    Code (Java):
    package me.MattieOfficial.UltimateServerTokens.commands;

    import java.io.File;

    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;

    import me.MattieOfficial.UltimateServerTokens.Main;
    import net.md_5.bungee.api.ChatColor;

    public class Tokens implements CommandExecutor {
     
        public static File mainFolder = new File("plugins/UltimateServerTokens");
        public static File dataFolder = new File("plugins/UltimateServerTokens/Data");
     
        public static File configFile = new File("plugins/UltimateServerTokens/config.yml");
        public static FileConfiguration config = new YamlConfiguration();
        public static File messagesFile = new File("plugins/UltimateServerTokens/messages.yml");
        public static FileConfiguration messages = new YamlConfiguration();
        public static File rewardsFile = new File("plugins/UltimateServerTokens/rewards.yml");
        public static FileConfiguration rewards = new YamlConfiguration();
     
        public static File userDataFile = new File("plugins/UltimateServerTokens/Data/userData.yml");
        public static FileConfiguration userData = new YamlConfiguration();

        public Tokens(Main main) {
            // TODO Auto-generated constructor stub
        }

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
         
            try {
             
                userData.load(userDataFile);
                messages.load(messagesFile);
                config.load(configFile);
             
             
         
                Player p = (Player) sender;
                String prefix = (ChatColor.translateAlternateColorCodes('&', ChatColor.translateAlternateColorCodes('&', config.getString("customize.prefix"))) + " ");
             
                if(args[0].equalsIgnoreCase("help")) { //line 48
                    if(args.length == 1) {
                        if(p.hasPermission("ust.player.help")) {
                         
                            //Player has permission,
                            p.sendMessage(prefix + ChatColor.DARK_AQUA + "Help");
                            p.sendMessage(ChatColor.DARK_AQUA + "/tokens" + ChatColor.WHITE + " - " + ChatColor.GRAY + "See how many tokens you have!");
                            p.sendMessage(ChatColor.DARK_AQUA + "/tokens send <player> <amount>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Send a certain number of tokens to a player!");
                            p.sendMessage(ChatColor.DARK_AQUA + "/tokens rewards" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Opens up the reward GUI!");
                            p.sendMessage(ChatColor.DARK_AQUA + "/tokens cheque write <name> <amount>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Write a cheque for other players to redeem!");
                            p.sendMessage(ChatColor.DARK_AQUA + "/tokens cheaue redeem <name>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Redeem a cheque wrote by another player!");
                         
                        } else {
                         
                            int amount = userData.getInt("user." + p.getUniqueId().toString() + ".tokenAmount");
                            String pname = p.getName();
                            String puuid = p.getUniqueId().toString();
                            String amountString = Integer.toString(amount);
                            p.sendMessage(prefix + ChatColor.translateAlternateColorCodes('&', messages.getString("noPerms").replace("%player_name%", pname).replace("%player_uuid%", puuid).replace("%amount%", amountString)));
                        }
                    } else {
                        int amount = userData.getInt("user." + p.getUniqueId().toString() + ".tokenAmount");
                        String pname = p.getName();
                        String puuid = p.getUniqueId().toString();
                        String amountString = Integer.toString(amount);
                        p.sendMessage(prefix + ChatColor.translateAlternateColorCodes('&', messages.getString("wrongUsageHelp").replace("%player_name%", pname).replace("%player_uuid%", puuid).replace("%amount%", amountString)));
                    }
                 
                }
                else if(args.length == 0) {
                    if(p.hasPermission("ust.player.tokens")) {
                     
                        //Check the amount of tokens a player has
                        try {
                         
                            userData.load(userDataFile);
                            config.load(configFile);
                            messages.load(messagesFile);
                         
                            int amount = userData.getInt("user." + p.getUniqueId().toString() + ".tokenAmount");
                            String pname = p.getName();
                            String puuid = p.getUniqueId().toString();
                            String amountString = Integer.toString(amount);
                         
                            p.sendMessage(prefix + ChatColor.translateAlternateColorCodes('&', messages.getString("currentAmount").replace("%player_name%", pname).replace("%player_uuid%", puuid).replace("%amount%", amountString)));
                         
                        } catch(Exception ex) {
                            ex.printStackTrace();
                        }
                     
                    } else {
                        //noPerms message
                    }
                }
             
         
            } catch(Exception ex) {
                ex.printStackTrace();
            }
            return false;
        }

    }
     
    Btw, im a vey new coder.. Maybe my code is messy, tell me when it is and how i can fix it.[/code]
     
  5. Dont catch every exception. Just catch the "IOException".

    Still: Please tell us what is in line 48 since you can't see code lines in the forum.

    Code (Java):
                if(args[0].equalsIgnoreCase("help")) { //line 48
                    if(args.length == 1) {
    Swap those if statements. Don't get the string from the array AND then check if the array has a string..
     
    • Agree Agree x 1
  6. In that case, it seems like you load up the config every time that a player uses that command, which you should only need to load it up once on the onEnable, then save it where needed.
    As for the error, you're getting an ArrayIndexOutOfBoundsException, and this is why:
    Code (Java):
    if(args[0].equalsIgnoreCase("help")) {
        if(args.length == 1) {
    You're trying to get the first argument before it's confirmed that there is a first argument.
     
  7. he had a li'l comment for it, lol
     
  8. there is a //line 48 after one of the lines ;), and i'll catch the IOException from now one
     
  9. Thanks! Didn't think of that. Any other things i could redo in my code to make it, for example more compact, ore less messy? And is it messy or not really? I'm really trying to improve my code ;)
     
  10. Yeah. Kinda missed that one.
     
  11. As mentioned before, removing that big ugly try catch method. Make a createConfig() method or something of that sort to load it once in the onEnable, then make a saveConfig()/loadConfig() method. Usually the difference is loading from the file (the previous save) and overwriting that old save with the new information that the FileConfiguration object has been changed to have. You shouldn't need to worry about a getConfig() method, since it's all in one class.
    The package name should also be all lowercase. Besides those few things, it's looking alright.