Assigning Random Int to ArrayList Index

Discussion in 'Plugin Development' started by Irantwomiles, Aug 9, 2015.

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

    Irantwomiles

    I'm making this plugin that requires 2 captains. I need a way to pick them so I have 2 random integers and I need a way to assign them to players in an arraylist. Then I would check if the 2 random integers are equal to an index in the arraylist so I can assign it to a specific player and that is where I'm having trouble. I don't know how to assign the random int to the index of the arraylist.
     
  2. I think it is list.set(index, object)
     
  3. Offline

    Chiller

    @Irantwomiles Just get a random number between 0 - (playerList.size() - 1),
    Then do playerList.get(randomInt), to get your random player,
    And just do that twice to get two players!
     
  4. Offline

    Irantwomiles

    Will the random int go through the size of my array?
     
  5. Offline

    Chiller

    @Irantwomiles Not if you do: new Random().nextInt(playerList.size() - 1)
     
  6. actually random.nextInt(n) will generate a number between 0 and n-1. If playerList is empty, an exception is thrown. So no need to use .size() - 1. Just .size()
     
  7. Offline

    Irantwomiles

    Is there a way to check who is index 4 in an array? like as in a string?
     
  8. Offline

    teej107

    Yes. Read the Java documentation for the ArrayList.
     
  9. Offline

    Irantwomiles

    Will do.
     
  10. list.get(4).equalsIgnoreCase("string")
     
  11. Offline

    Irantwomiles

    Ty so much.

    So this is what I did
    Code:
    join.get(captain1).equalsIgnoreCase(player.getName());
    
    and in the message it said "False" kind of confused.
    Edit: Captain1 = 0 and join is my arrayList
    Edit2: I now see that it returns a boolean. Anyway to return a string?

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

    SuperOriginal

    Assuming you're printing out the Boolean in a message, the player name isn't equal to the first element in the list then.
     
  13. Offline

    Irantwomiles

    Well I want it to print out who's ever name is in the index of the int captain1. So if captain1 = 1 I want it to print out who's ever name is in the index of 1;

    So I did join.get(captain1).toString() and that seems to do what I wanted it to do, is that bad practice or is anything wrong with that? @SuperOriginal @FisheyLP @teej107

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

    teej107

    You may be fine from this but that code will throw a NPE if the #get() method returns null.
     
  15. Offline

    Irantwomiles

    Ya I've seen it happen.
     
Thread Status:
Not open for further replies.

Share This Page