-1

I want to alphabetize the names of all online players. and then get 1 random player from that

pppery
  • 3,731
  • 22
  • 33
  • 46
vitekform
  • 25
  • 5

1 Answers1

2

You can use Bukkit.getOnlinePlayers() to get all the online players.

Then you can use the sort() function to sort them and then use the Random class to get a casual player from the list.

Example:

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

public class YourPluginClass {

    public void selectRandomPlayer() {
        // Step 1: Get the online players
        Player[] onlinePlayers = Bukkit.getOnlinePlayers().toArray(new Player[0]);

        // Step 2: Alphabetize the player names
        Arrays.sort(onlinePlayers, Comparator.comparing(Player::getName));

        // Step 3: Select a random player
        if (onlinePlayers.length > 0) {
            Random random = new Random();
            int randomIndex = random.nextInt(onlinePlayers.length);
            Player randomPlayer = onlinePlayers[randomIndex];
        } else {
            // No players online
        }
    }
}

baggiogiacomo
  • 179
  • 10