Solved My function to get a random player doesn't work properly

Discussion in 'Plugin Development' started by GeekyMe97, Oct 29, 2012.

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

    GeekyMe97

    Hello!
    I've got a function which purpose is to return a random online player.
    However, when I have 2 players online, it keeps returning the same player.
    When I have 3 players online, one of the players never gets returned.

    This is my function:
    Code:JAVA
    1. public static Player getRandomPlayer(Hunted plugin){
    2. Player randomPlayer = null;
    3.  
    4. Player[] player = plugin.getServer().getOnlinePlayers();
    5. //Only return a player when there is two or more players online
    6. if (player.length >= 2) {
    7. randomPlayer = player[new Random().nextInt(player.length - 1)];
    8. }
    9.  
    10. return randomPlayer;
    11. }


    Any idea what could be wrong?
    Keep in mind that I don't have too much experience with Java.

    Help would be appreciated :)

    EDIT;
    This is the code for the class that uses the function!
    Thought it might be useful.
    Show Spoiler

    Code:JAVA
    1. package com.gmail.geekyme97.hunted;
    2.  
    3. import org.bukkit.ChatColor;
    4. import org.bukkit.entity.Player;
    5.  
    6. public class HuntPlayer implements Runnable{
    7.  
    8. private Hunted plugin;
    9.  
    10. public HuntPlayer(Hunted plugin) {
    11. this.plugin = plugin;
    12. }
    13.  
    14. @Override
    15. public void run() {
    16. // TODO Auto-generated method stub
    17. Player player = GeneralMethods.getRandomPlayer(plugin);
    18. if (player != null){
    19. GeneralMethods.sendMessageToAllPlayers(
    20. ChatColor.GREEN + player.getName() +
    21. ChatColor.BLUE + " is located at " +
    22. ChatColor.GREEN + player.getLocation().getX() + ", " + player.getLocation().getY() + ", " + player.getLocation().getZ() +
    23. ChatColor.BLUE + "!", true, plugin);
    24. GeneralMethods.sendMessageToAllPlayers(ChatColor.BLUE + "Hunt him down!", plugin);
    25. }
    26. }
    27.  
    28. }
    29.  

     
  2. Offline

    Timr

    Are there two or more players online when you try to use the function? It should work.
     
  3. Offline

    Njol

    Random.nextInt(x) returns a random number between 0 and x-1 (both inclusive), thus you don't have to manually subtract 1:
    randomPlayer = player[new Random().nextInt(player.length)];
     
  4. Offline

    GeekyMe97

    I forgot about that~
    Thanks, works now! :)
     
Thread Status:
Not open for further replies.

Share This Page