Having Trouble With Array Lists

Discussion in 'Plugin Development' started by TheChinski, Apr 28, 2012.

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

    TheChinski

    I've been having a go at making a simple chat plugin, but the Array Lists have got me stuck. For some reason, even if I have the perms, I dont get on the list. When i'm opped, however, I come up on all the lists - But if I type /perm dump (Check a players perms) while opped, the perms necessary dont come up on the list...

    Code:
    package com.sludgecraft.WhosOnline;
     
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;
     
     
    public class WhosOnline extends JavaPlugin
    {
        List<Player> Group1 = new ArrayList<Player>();
        List<Player> Group2 = new ArrayList<Player>();
        List<Player> Group3 = new ArrayList<Player>();
        List<Player> Group4 = new ArrayList<Player>();
        List<Player> Group5 = new ArrayList<Player>();
        List<Player> Group6 = new ArrayList<Player>();
        public static WhosOnline plugin;
        Logger log;
     
        @Override
        public void onEnable() {
            final FileConfiguration config = this.getConfig();
            config.options().header("You can change these defaults to whatever you like:");
            config.addDefault("Groups.Group1", "Founder");
            config.addDefault("Groups.Group2", "");
            config.addDefault("Groups.Group3", "");
            config.addDefault("Groups.Group4", "");
            config.addDefault("Groups.Group5", "");
            config.addDefault("Groups.Group6", "");
            new myPlayerListener(this);
            log = this.getLogger();
            log.info("WhosOnline Has Been Enabled... O.o");
            config.options().copyDefaults(true);
            saveConfig();
            config.getString("Groups.Group1");
            config.getString("Groups.Group2");
            config.getString("Groups.Group3");
            config.getString("Groups.Group4");
            config.getString("Groups.Group5");
            config.getString("Groups.Group6");
            for(Player player: getServer().getOnlinePlayers()) {
                if(player.hasPermission("whosonline.group.1"))
                {
                    Group1.add(player);
                }
                if(player.hasPermission("whosonline.group.2"))
                {
                    Group2.add(player);
                }
                if(player.hasPermission("whosonline.group.3"))
                {
                    Group3.add(player);
                }
                if(player.hasPermission("whosonline.group.4"))
                {
                    Group4.add(player);
                }
                if(player.hasPermission("whosonline.group.5"))
                {
                    Group5.add(player);
                }
                if(player.hasPermission("whosonline.group.6"))
                {
                    Group6.add(player);
                }
                else
        {
                    if(!player.hasPermission("whosonline.group.1"))
                    {
                        Group1.remove(player);
                    }
                    if(!player.hasPermission("whosonline.group.2"))
                    {
                        Group2.remove(player);
                    }
                    if(!player.hasPermission("whosonline.group.3"))
                    {
                        Group3.remove(player);
                    }
                    if(!player.hasPermission("whosonline.group.4"))
                    {
                        Group4.remove(player);
                    }
                    if(!player.hasPermission("whosonline.group.5"))
                    {
                        Group5.remove(player);
                    }
                    if(!player.hasPermission("whosonline.group.6"))
                    {
                        Group6.remove(player);
                    }
        }
                }
            }
        public void onDisable(){
            log.info("WhosOnline Has Gone To Sleep...");
        }   
        public class myPlayerListener implements Listener
        {
            public myPlayerListener (WhosOnline plugin)
            {
                plugin.getServer().getPluginManager().registerEvents(this, plugin);
            }
        }
        int playerlist = Bukkit.getOnlinePlayers().length;
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            if(cmd.getName().equalsIgnoreCase("who")){
                String op1 = this.getConfig().getString("Groups.Group1");
                String op2 = this.getConfig().getString("Groups.Group2");
                String op3 = this.getConfig().getString("Groups.Group3");
                String op4 = this.getConfig().getString("Groups.Group4");
                String op5 = this.getConfig().getString("Groups.Group5");
                String op6 = this.getConfig().getString("Groups.Group6");
                ((Player)sender).sendMessage(ChatColor.BLUE + "There are " + ChatColor.BLACK + '[' + ChatColor.RED + playerlist + ChatColor.BLACK + ']' + ChatColor.BLUE + " players online:");
                ((Player)sender).sendMessage("");
                ((Player)sender).sendMessage(op1 + ": " + Group1);
                ((Player)sender).sendMessage(op2 + ": " + Group2);
                ((Player)sender).sendMessage(op3 + ": " + Group3);
                ((Player)sender).sendMessage(op4 + ": " + Group4);
                ((Player)sender).sendMessage(op5 + ": " + Group5);
                ((Player)sender).sendMessage(op6 + ": " + Group6);
                return true;
            }
        return false;
        }
    }
    
    And just incase its a problem here, this is my plugin.yml:

    Code:
    name: WhosOnline
    main: com.sludgecraft.WhosOnline.WhosOnline
    version: 0.1
     
    commands:
      who:
          description: Who's Online? I don't know...
          usage: /{command}
          permission-message: No Perms Sorry :/
    permissions:
        whosonline.group.1:
            description: Lists The Player Under Group 1...
            default: false
        whosonline.group.2:
            description: Lists The Player Under Group 2...
            default: false
        whosonline.group.3:
            description: Lists The Player Under Group 3...
            default: false
        whosonline.group.4:
            description: Lists The Player Under Group 4...
            default: false
        whosonline.group.5:
            description: Lists The Player Under Group 5...
            default: false
        whosonline.group.6:
            description: Lists The Player Under Group 6...
            default: false
     
  2. Offline

    Nitnelave

    Just for info, your "else" after the 6 "if(player.hasPermission)" is only for the last test. You might want to do "if", else if, else if, ... , else
     
  3. Offline

    TheChinski

    I had a little mess around with it, and I have changed it now - Thankyou :)

    I am now stuck at this point. Everything is working (Thats meant to be working) but for some reason, I just cant get the lists to work :mad:

    When opped, I come up on all of them, but otherwise, no matter how I warp the permissions, I get nothing... :/
     
  4. Offline

    Nitnelave

    Grant yourself several permissions in different ways (default permissions, group permissions, personal permissions, etc...) then have your plugin cycle through them and tell you which one you have (while you're not op, of course).
     
  5. Offline

    TheChinski

    Ok, now even opped, I dont come up on the list :S

    I have been playing around with it - And I have been adding some anti-null things to do with my config...

    Code:
    package com.sludgecraft.WhosOnline;
     
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
     
    public class WhosOnline extends JavaPlugin
    {
        List<Player> Group1 = new ArrayList<Player>();
        List<Player> Group2 = new ArrayList<Player>();
        List<Player> Group3 = new ArrayList<Player>();
        List<Player> Group4 = new ArrayList<Player>();
        List<Player> Group5 = new ArrayList<Player>();
        List<Player> Group6 = new ArrayList<Player>();
        public static WhosOnline plugin;
        Logger log;
     
        @Override
        public void onEnable() {
            final FileConfiguration config = this.getConfig();
            config.options().header("You can change these defaults to whatever you like:");
            config.addDefault("Groups.Group1", "Founder");
            config.addDefault("Groups.Group2", " ");
            config.addDefault("Groups.Group3", " ");
            config.addDefault("Groups.Group4", " ");
            config.addDefault("Groups.Group5", " ");
            config.addDefault("Groups.Group6", " ");
            new myPlayerListener(this);
            log = this.getLogger();
            log.info("WhosOnline Has Been Enabled... O.o");
            config.options().copyDefaults(true);
            saveConfig();
            config.getString("Groups.Group1");
            config.getString("Groups.Group2");
            config.getString("Groups.Group3");
            config.getString("Groups.Group4");
            config.getString("Groups.Group5");
            config.getString("Groups.Group6");
        }
        @EventHandler (priority = EventPriority.HIGHEST)
            public void onPlayerJoin(final PlayerJoinEvent event) {
            for(Player player: getServer().getOnlinePlayers()) {
                if(player.hasPermission("whosonline.group.1"))
                {
                    Group1.add(player);
                }
                if(player.hasPermission("whosonline.group.2"))
                {
                    Group2.add(player);
                }
                if(player.hasPermission("whosonline.group.3"))
                {
                    Group3.add(player);
                }
                if(player.hasPermission("whosonline.group.4"))
                {
                    Group4.add(player);
                }
                if(player.hasPermission("whosonline.group.5"))
                {
                    Group5.add(player);
                }
                if(player.hasPermission("whosonline.group.6"))
                {
                    Group6.add(player);
                }
                if(!player.hasPermission("whosonline.group.1"))
                {
                    Group1.remove(player);
                }
                if(!player.hasPermission("whosonline.group.2"))
                {
                    Group2.remove(player);
                }
                if(!player.hasPermission("whosonline.group.3"))
                {
                    Group3.remove(player);
                }
                if(!player.hasPermission("whosonline.group.4"))
                {
                    Group4.remove(player);
                }
                if(!player.hasPermission("whosonline.group.5"))
                {
                    Group5.remove(player);
                }
                if(!player.hasPermission("whosonline.group.6"))
                {
                    Group6.remove(player);
                }
            }
        }
        public void onDisable(){
            log.info("WhosOnline Has Gone To Sleep...");
        }   
        public class myPlayerListener implements Listener
        {
            public myPlayerListener (WhosOnline plugin)
            {
                plugin.getServer().getPluginManager().registerEvents(this, plugin);
            }
        }
        int playerlist = Bukkit.getOnlinePlayers().length;
        @EventHandler (priority = EventPriority.HIGHEST)
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            if(cmd.getName().equalsIgnoreCase("who")){
                String op1 = this.getConfig().getString("Groups.Group1");
                String op2 = this.getConfig().getString("Groups.Group2");
                String op3 = this.getConfig().getString("Groups.Group3");
                String op4 = this.getConfig().getString("Groups.Group4");
                String op5 = this.getConfig().getString("Groups.Group5");
                String op6 = this.getConfig().getString("Groups.Group6");
                ((Player)sender).sendMessage(ChatColor.BLUE + "There are " + ChatColor.BLACK + '[' + ChatColor.RED + playerlist + ChatColor.BLACK + ']' + ChatColor.BLUE + " players online:");
                ((Player)sender).sendMessage("");
                if(op1 != " ") {
                    if(Group1 != null) {
                        ((Player)sender).sendMessage(op1 + ": " + Group1);
                    }
                }
                if(op2 != " ") {
                    if(Group1 != null) {
                        ((Player)sender).sendMessage(op2 + ": " + Group2);
                    }
                }
                if(op3 != " ") {
                    if(Group1 != null) {
                        ((Player)sender).sendMessage(op3 + ": " + Group3);
                    }
                }
                if(op4 != " ") {
                    if(Group1 != null) {
                        ((Player)sender).sendMessage(op4 + ": " + Group4);
                    }
                }
                if(op5 != " ") {
                    if(Group1 != null) {
                        ((Player)sender).sendMessage(op5 + ": " + Group5);
     
                    }
                    if(op6 != " ") {
                        if(Group1 != null) {
                        }
                        ((Player)sender).sendMessage(op6 + ": " + Group6);
                    }
                }
                return true;
            }
            return false;
        }
    }
    
    I just cant see any reason why it wouldn't be working...
     
  6. Offline

    Nitnelave

    How about
    if(player.hasPermission("whosonline.group.1"))
    Group1.add(player);
    else
    Group1.remove(player);

    for aesthetics ^^ and speed.

    Also for your strings, I believ (can't check right now) that there's a String.isEmpty() check, rather than checking against "" (and also, checking against " " will always be false, mind the space)
     
  7. Offline

    TheChinski

    Thankyou - Much tidier :)

    Although, I still have the problem of the list not appearing to be working :/ Oh, and the " "'s was my attempt at hiding them :p Because if I told it to not include for null, it would still find them due to in the config generation, the blank fields were set as ''...
     
  8. Offline

    Nitnelave

    If you detect the permission, have it display a message on the console, so you can track if the player has the permissions, or if the problem comes from somewhere else.
     
  9. Offline

    TheChinski

    Got the lists working! :D

    Im sure ill be back with more errors soon though... :p

    EDIT: XD - We posted them at exactly the same time...

    It was fixed by moving all the
    Code:
                    if(player.hasPermission("whosonline." + op1))
                        Group1.add(player);
                    else
                        Group1.remove(player);
    's into the onCommand :D

    Hmmm, 2 mins before a problem? :p

    When I start the plugin for the first time, it works fine. Although after a reload/stop and start the server, all the other groups which should be removed come up. Like this:

    Founder: (Blah blah blah)
    :
    :
    :
    :
    :

    And when my name comes up, it comes up as [CraftPlayer{name=TheChinski}]

    Otherwise, its working :p

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
  10. Offline

    Nitnelave

    1000th post!
    Hem, sorry. So, the groups show up because Group2!=null but is still empty... And I guess your op2 == "" and is != from " " (space). Also, displaying a group, like that, is NOT the way you want it. You should do a method, with a for each loop, that returns a String that is suitable for display.
     
  11. Offline

    Scyntrus

    Group1.add(player);
    Should be
    Group1.add(player.getName());
     
  12. Offline

    TheChinski

    -The error on 'add' when (player.getName()) is used...

    I think its something to do with this line:
    for(Player player: getServer().getOnlinePlayers()) {

    Have I got the right everything? I am trying to get the names of everyone online, I think i'm getting something abit more detailed...
     
  13. Offline

    marky1991

    You changed these lines

    Code:
       List<Player> Group1 = new ArrayList<Player>();
        List<Player> Group2 = new ArrayList<Player>();
        List<Player> Group3 = new ArrayList<Player>();
        List<Player> Group4 = new ArrayList<Player>();
        List<Player> Group5 = new ArrayList<Player>();
        List<Player> Group6 = new ArrayList<Player>();
    
    to be List<String>, didn't you? You're adding strings to them now instread of the actual player objects.
     
  14. Offline

    Scyntrus

    Ok, do you want your list to be of the Players, or the player's names (String)?

    You can't just convert a list of players into a string...

    if you want, you can print out the list of the players names like this:

    String message = "";
    for (Player p : Group1) {
    message += p.getName() + ", ";
    }
    ((Player)sender).sendMessage(message);

    When you convert a Player into a String, you don't get the actual player name but the name of the object. You can't just flip flop between Player objects and their String names.
     
  15. Offline

    TheChinski

    I wub you :p

    Thankyou so much - Finally got it working...

    I changed :
    if(op1 != "") {
    ((Player)sender).sendMessage(op1 + ": " + Group1);
    }
    }

    to:
    for (Player p : Group2) {
    if(op2 != "") {
    ((Player)sender).sendMessage(op2 + ": " + p.getName());
    }
    }

    And that has also fixed the Null problem :D


    Thanks again for all your help, and tolerating my lack of coding skill :)

    [diamond][diamond][diamond]
     
  16. Offline

    Nitnelave

    Wahoo! You're going to send 50 lines of message if they are 50 people online! (and by the way, you're going to do 50 check for op!=""
    you should do like scyntrus said, building a String with all of the names, then sending the string.
     
  17. Offline

    TheChinski

    Yeah, just found that out :p

    Ad everytime I enter /Who, the player is added to the list again... XD

    Ah well, a few bugs to iron out :p

    Thanks,

    So, (I hope i dont sound too hopeless in saying this) how exactly would I change the list into a string?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
  18. Offline

    Nitnelave

    Well, it depends what kind of list you have. If you really need a list of Players and not of String, you could do
    String message = op1;
    for(Player p : list) <opening bracket>
    message += p.getName() + ", ";
    <closing bracket>
     
  19. I used that before but at someone pointed out that it is not that efficient. And yes, it's not. Every time you call function on a string a new instance is created. Meaning the longer the string gets, the more expensive it is using methods on it. Using the StringBuilder, you can make it more efficient.

    Show Spoiler
     
  20. Offline

    marky1991

    Meh. That inefficiency is pointed out way too often. Unless he's iterating over a large number of players (considering the most it's likely to be is under 200, this is unlikely), the naive concatenation approach could actually be faster than using a stringbuilder. And either way, the difference in speed is likely to be negligible.

    edit: Added the last sentence.
     
  21. Offline

    TheChinski

    What i'm getting now is:

    Founder: Username1
    Founder: Username2

    But what im looking for is:

    Founder: Username1, Username2,

    I found a guide a few days back which really explained all this sort of thing really well, but I cant find it now... :/
     
  22. Offline

    AstramG

    By the way, I am very new to Java but I'm pretty sure you can make a loop instead of writing it a bunch of times for each group #.
     
  23. Offline

    Nitnelave

    Indeed, you can have an array of List, and an array of String (for the list name), and then:
    Code:java
    1.  
    2. for(int i = 0; i<5; i++) {
    3. String message = groups_names[i];
    4. for(Player p : list_players){
    5. message += p.getName() + ", ";
    6. }
    7. sender.sendMessage(message);
    8. }
    9. [/i]

    Here, the ArrayLists Group1, Group2, etc ... are stored in the list_players, and the op1, op2, etc... in the groups_names. This more flexible structure allows you to have a variable number of groups. You can define groups in the config, and instead of having 6 groups, 4 of them useless, you could use only 2 groups.
     
  24. Offline

    TheChinski

    Wow - Eclipse isnt very happy about loops... :S It seems that whenever there's something to do with loops, its giving an error... Infact, the only bit which doesnt give errors is for(int i =0; i<5; i++){

    Ok, I have never used loops before and i'm tired. Not a very co-operative pair. I'll have another shot in the morning, but just in case i'm wandering hopelessly in the entirely wrong direction:

    Code:
    package com.sludgecraft.WhosOnline;
     
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerQuitEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
     
    public class WhosOnline extends JavaPlugin
    {
        List<String> Group1 = new ArrayList<String>();
        public static WhosOnline plugin;
        Logger log;
     
        public void onEnable() {
            for(int i = 0; i<5; i++) {
            final FileConfiguration config = this.getConfig();
            config.options().header("You can change these defaults to whatever you like:");
            config.addDefault("Group"[i]);[/I]
            new myPlayerListener(this);
            log = this.getLogger();
            log.info("WhosOnline Has Been Enabled... O.o");
            config.options().copyDefaults(true);
            saveConfig();
            config.getString("Group"[i]);
        }
        }
        public void onDisable(){
            log.info("WhosOnline Has Gone To Sleep...");
        }   
        public class myPlayerListener implements Listener
        {
            public myPlayerListener (WhosOnline plugin)
            {
                plugin.getServer().getPluginManager().registerEvents(this, plugin);
            }
        }
        @EventHandler (priority = EventPriority.HIGHEST)
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            if(cmd.getName().equalsIgnoreCase("who")){
                int playerlist = Bukkit.getOnlinePlayers().length;
                int maxlist = Bukkit.getMaxPlayers();
                for(Player player: getServer().getOnlinePlayers()) {
                    String op1 = this.getConfig().getString("Groups.Group1");
                    for(int i = 0; i<5; i++) {
                    if(player.hasPermission("whosonline."[i]))
                        Group[i].add(player.getName());
                    else
                        Group[i].remove(player);
                    }
                }
                for(int i = 0; i<5; i++) {
                ((Player)sender).sendMessage(ChatColor.BLUE + "There are " + ChatColor.BLACK + '[' + ChatColor.RED + playerlist + "/" + maxlist + ChatColor.BLACK + ']' + ChatColor.BLUE + " players online:");
                ((Player)sender).sendMessage("");
                String message = Group[i];
                for(Player p : list_players){
                    message += p.getName() + ", ";
                }
                sender.sendMessage(message);
                }
                return true;
            }
            return false;
        }
    }
    
    Every time I use i'm getting an error. Im guessing i've missed out obvious things, but I can't see them :p

    Thanks, :)


    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
  25. Offline

    Scyntrus

    It'd be nice to see the error message. In case you wanted more help.
     
  26. Offline

    Nitnelave

    Wahoo! You used loops everywhere! Well, you should get more informations about how to handle loops and arrays... But for a quick fix, basically, a loop repeats the action in between the {}, but for different values of a variable, or while a certain condition is met. In your specific case, the loop I gave you does the action 6 times, with the variable i having at first the value 0, then 1, then 2, etc... up to 5. But you should only repeat the actions that will change when i (the variable) changes! For example, the
    FileConfiguration config = this.getConfig(); always has the same result, whatever the value of i, and you don't want to do this 6 times!
    Basically, you need an array of list (an array of arrayList, in your case), so you will have
    List<String> groupList[] = new ArrayList<String>()[6];
    And then, each time you have something to do with group1, group2, etc... you do a loop. For example :
    for(int i = 0; i<5; i++) {
    if(player.hasPermission("whosonline." + i))
    groupList(i).add(player.getName());
    else
    groupList(i).remove(player.getName());
    }

    Careful! here, I used (i) instead of square brackets, because that stupid editor think that mean italic. But what I meant was square brackets around the i, as for the rest of this post.

    Here, you had 3 errors : first, Group is not a variable, you didn't declare it. What you declared, though is the variable Group1. I see what you tried to do, but that's not how you do it. Get some more info on arrays, too.
    The second error was on the "whosonline."(i) : the string is not an array, so you can't take the ith element. But you can manipulate i as a number, and add it at the end of the string, as I did.
    The last one was in Group(i).remove(player) : You add Strings to the list, and you want to remove Players? It will never find it, so never remove anything. You add the player's name, so you have to remove the player's name too.
    Well, I didn't check all your code, but check that, you might also want to check if you know the basic with a java tutorial, and then if you need more help, post again!

    Good luck!
     
Thread Status:
Not open for further replies.

Share This Page