Iterating through a list of the online players

Discussion in 'Plugin Development' started by Shzylo, Oct 12, 2013.

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

    Shzylo

    I have created an ArrayList of online players that I want to be printed out every time that the user types a command; I have no prior knowledge about this really, but I was attempting a guess like this (but it failed):

    Code:
    ListIterator<Player> humans = ZombieEscape.online.listIterator();
     
    sender.sendMessage(ChatColor.GREEN + "Online: " + humans);
    return true;
    How would I get it to iterate through the list and print out the player names?
     
  2. Offline

    The_Doctor_123

    Code:java
    1. String OnlinePlayers = "Online Players: ";
    2. for (Player player : humans)
    3. {
    4. OnlinePlayers.concat(player.getName() + ", ");
    5. }
     
    Shzylo and Jozeth like this.
  3. Offline

    Garris0n

    Yes, but horribly inefficient, and you'd have to do OnlinePlayers = OnlinePlayers.concat(player.getName() + ", "); as Strings are immutable.

    Code:java
    1. public static String getOnlinePlayers(List<String> players){ //Don't save player instances.
    2.  
    3. StringBuilder onlinePlayers = new StringBuilder( ); //Create a new StringBuilder
    4.  
    5. for(String s : players) //Iterate.
    6. onlinePlayers.append(", ").append(s); //Append the ", name" on the end.
    7.  
    8. if(onlinePlayers.length > 2) //It will be less than two if there are no players in the list.
    9. return "Online Players: " + onlinePlayers.subString(2); //Substring to remove the ", " prefix.
    10.  
    11. return "Online Players: "; //There weren't any players in it anyway, no need to concat the blank string on the end.
    12.  
    13. }
     
    Shzylo likes this.
  4. Offline

    Shzylo

    Thank you guys so much for the help! There were a couple issues I had to work around, but I got it solved. You both deserve a like :p
     
Thread Status:
Not open for further replies.

Share This Page