Solved Selecting random string from config.yml

Discussion in 'Plugin Development' started by BagduFagdu, May 25, 2015.

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

    BagduFagdu

    So I have a giveaway plugin, and I'm trying to figure out how to select a random string from the config.yml.
    I know for fact that I can use switch statement, but when it comes to a list of 50+ items, what's the best method to randomize something.

    Code:
    # Config.yml Rewards:
      - diamonds
      - gold
      - emeralds
      - potions
      - 46 other items…
    So, using a loop I get all items. Now, since I've got all items from the list, how can I just choose one?
    Code:
    for(String random : plugin.getConfig().getStringList("# Config.yml Rewards")) {
       //
    }
     
  2. Offline

    nverdier

    @BagduFagdu List#get(int index) just make the index a random number in the range of the size of the list.
     
  3. Offline

    BagduFagdu

    Thanks, @nverdier .
    This is what I did:

    Code:
    public static String chooseRandom() {
            ArrayList<String> list = (ArrayList<String>) plugin.getConfig().getStringList("# Crate Rewards");
            Random random = new Random();
            int selector = random.nextInt(list.size());
            String chosenReward = list.get(selector);
            list = null; random = null; selector = -1;
            return chosenReward;
    }
     
  4. Offline

    nverdier

    @BagduFagdu Use List<String> instead of ArrayList. Use ThreadLocalRandom#current()#nextInt(... instead of creating a new Random each time you call the method. No need to create 'selector', just in-line it.
     
    BagduFagdu likes this.
  5. @nverdier Using hash generally represents a non-static method, current() is static ;)


    @BagduFagdu Also, there's no need to null/-1 your objects & int at the end of the method. Not sure why you're doing that.
     
    BagduFagdu likes this.
Thread Status:
Not open for further replies.

Share This Page