1.8.8 If HashMap exists do something

Discussion in 'Spigot Plugin Development' started by SammyProXCoding, Sep 14, 2021.

  1. So im currently working on a practice plugin and want to get if the player is queued for nodebuff (return true or false), Now, i made a command (/queue) which queues you into NoDebuff, now, everytime the player does /queue, the HashMap completely resets...
    Code (Text):
    package me.bright.practice.commands;

    import com.sun.org.apache.xpath.internal.operations.Bool;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    import java.util.HashMap;

    public class Start implements CommandExecutor {
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.BOLD + "<" + ChatColor.RED + "*" + ChatColor.RESET + ChatColor.BOLD + ">" + ChatColor.RED + "This command can only be executed by a player!");
                return true;
            } else {
                Player p = (Player) sender;
                HashMap<Player, Boolean> NoDebuffQueue = new HashMap<Player, Boolean>();
                NoDebuffQueue.put(p, true);
                return true;
            }
        }
    }
     
    Is there a way to make the HashMap on start of the plugin and accessible from other classes?
     
  2. Your HashMap resets because a new instance of it is being generated each time you do /queue. You'll probably want to make a HashMap in the main class and provide some getter for it
     
  3. Yes, i tried but it didnt work or something, i cant remember.
    EDIT: Never mind i got it to work...
     
  4. I'm not that good at java still learning, but just create a static HashMap in your main class, and add a getter for it, then from there you can do stuff
     
  5. Static isn't necessary in this case, and should be avoided if you don't know what exactly it does and and why you're using it. You just need to store and be able to access an instance of the class that contains the HashMap.
     
  6. Did it, but doesnt work :/
    Main Class:
    Code (Java):
    package me.bright.practice;

    import me.bright.practice.commands.FlyCommand;
    import me.bright.practice.commands.queue;
    import me.bright.practice.events.Events;
    import org.bukkit.Bukkit;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;

    import java.util.HashMap;

    public final class Main extends JavaPlugin {
        public static final String ANSI_RESET = "\u001B[0m";
        public static final String ANSI_BLACK = "\u001B[30m";
        public static final String ANSI_RED = "\u001B[31m";
        public static final String ANSI_GREEN = "\u001B[32m";
        public static final String ANSI_YELLOW = "\u001B[33m";
        public static final String ANSI_BLUE = "\u001B[34m";
        public static final String ANSI_PURPLE = "\u001B[35m";
        public static final String ANSI_CYAN = "\u001B[36m";
        public static final String ANSI_WHITE = "\u001B[37m";
        public static HashMap<Player, Boolean> NoDebuffQueued = new HashMap<Player, Boolean>();
        public static HashMap<String, Integer> Queue = new HashMap<String, Integer>();
        @Override
        public void onEnable() {
            System.out.println(ANSI_BLUE + "_____________________");
            System.out.println(ANSI_CYAN + "Starting Bright Practice v1");
            System.out.println(ANSI_PURPLE + "IF ANY ERRORS, PLEASE REPORT TO ChillBright#4622");
            System.out.println(ANSI_BLUE + "_____________________" + ANSI_RESET);
            Bukkit.getPluginManager().registerEvents(new Events(), this );
            getCommand("fly").setExecutor(new FlyCommand());
            getCommand("queue").setExecutor(new queue());

        }

        @Override
        public void onDisable() {
            // Plugin shutdown logic
        }
    }
     
    Queue Command Class:
    Code (Text):
    package me.bright.practice.commands;

    import com.sun.org.apache.xpath.internal.operations.Bool;
    import me.bright.practice.Main;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    import java.util.HashMap;

    public class queue implements CommandExecutor {
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.BOLD + "<" + ChatColor.RED + "*" + ChatColor.RESET + ChatColor.BOLD + ">" + ChatColor.RED + "This command can only be executed by a player!");
                return true;
            } else {
                Player p = (Player) sender;
                if(args[0].equalsIgnoreCase("ndb")){
                    if(Main.Queue.get("NoDebuff") == 1){
                        p.sendMessage("2 people queued. Starting...");
                        Main.Queue.remove("NoDebuff");
                    } else {
                        p.sendMessage("You queued for NoDebuff.");
                        Main.NoDebuffQueued.put(p, true);
                        Main.Queue.put("NoDebuff", 1);
                    }
                }



                return true;
            }
        }
    }
     
    Error:

    Code (Text):
    org.bukkit.command.CommandException: Unhandled exception executing command 'queue' in plugin BrightPractice v1.0-SNAPSHOT
            at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:641) ~[server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1162) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:997) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:45) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:1) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [server.jar:git-Spigot-db6de12-18fbb24]
            at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) [?:?]
            at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) [?:?]
            at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:715) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [server.jar:git-Spigot-db6de12-18fbb24]
            at java.base/java.lang.Thread.run(Thread.java:831) [?:?]
    Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.HashMap.get(Object)" is null
            at me.bright.practice.commands.queue.onCommand(queue.java:22) ~[?:?]
            at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[server.jar:git-Spigot-db6de12-18fbb24]
            ... 15 more
     
  7. Check Main.Queue.get("NoDebuff") to null, and try to work with it
     
  8. Good suggestion, bad practice.
    Use Main.Queue.containsKey("NoDebuff") to check if the value exists or not.
     
  9. Good suggestion but static abuse.
     
  10. I had a hard time reading this madness, I don't know how necessary "Main.Queue" is since I see it useless, you could do what I am about to say:
    1: Use dependency injection with the constructor.
    2: Define the Map when starting the plugin.
    3: Make getters to get the list you want.
    The error appears since you are getting directly and not checking, give NPE, use Map#containsKey(String); (In your case it is "String") to check if it is present.
    And as I could see in that command, your "NoDebuff" will always be 1, since you don't do anything else to increase or decrease the value. Please explain me what you want to achieve with the "NoDebuff", if it is to store how many are in the queue, then it is totally unnecessary, you could get the current queue size and that's it.
     
  11. Static abuse is for plugin instances (in plugins at least), because you don't know if the plugin is loaded or not and/or if the static value was initializated in the first place and that leads to (unexpected) errors.
    He initializated the static properly.
    Imho.
     

  12. You clearly don't know when to use the static keyword and when not to.
    But that's normal here in the Minecraft plugin scene.
     
  13. Oi, what da bloody hell? Chill mates.
     
    • Funny Funny x 1
  14. https://github.com/yannicklamprecht...worldborder/plugin/WorldBorderPlugin.java#L21
    Is that you?
    In java there's no thing as "static abuse" if the static value was initializated at the start of the execution (just like in OOP when you initialize a new instance and you have final values).
     
    1. You probably see the deprecation notice. You need to use the Service API of Bukkit when the deprecated part is dropped. The API is exposing specific part in a controlled matter.
    2. Having your maps and shit fully static like OP does, is not a facade thing. He basically exposes all variable to the public. Every piece of Software can modify the values of that maps. There is a reason for using encapsulation and dependency injection
    That's totally wrong. See points above. It is static abuse. You can define constants for stuff, but a Map how OP use it, is not a constant. You also get a memory issue because stuff like that won't be cleared properly but that's another thing.

    You probably need to learn what the concept of OOP is.
     
  15. None of what you tried to say made him solve the problem. He is a newbie after all and now he probably still trying to make sense of what people tried to point out.
    I know what OOP is and how and why is used.
    Is not something I would code myself, not "exposing" everything, but in his case... he asked for help on one problem.
    I forgot how imbecile can people be on spigot forums. Judging everything you say and arguing with you for no reason even if you have a point in what you say. Oopsie, my bad.
     
  16. Strahan

    Benefactor

    Well... newbie or not, it's best to clip bad habits early so they don't fester lol. One can certainly solve problems and produce a fully functioning plugin that looks to do the job perfectly yet the codebase could be a horrorshow of spaghetti code, terrible lack of optimization and bad practices abound. Letting someone limp by just to get the job done may help their immediate goal, but won't help their long term viability as a developer.

    Not that it's any of our responsibilities to help them grow as programmers, but it doesn't hurt when someone points out those bad practices.
     
    • Agree Agree x 1
  17. My point was simple: he said that is static abuse then I've pointed out that it is not, explaining him why is not. He changed to the fact that he shouldn't use public access everywhere and encapsulation is the way to go. I can't agree more, you wouldn't want anyone to access your plugin variables or mapped values unless you allowing that.
    Also, there are (still, after all these years) some popular plugins which their codebase are trash...
     
    • Agree Agree x 2
  18. I already fixed it. But forgot about my post ;)