Jump to content
  • 0
Taras

[562] Working with arrays + random()

Question

I'm trying to make a lootable chest that gives random items etc... This is my code at the moment.

final static java.util.Random RANDOM = new java.util.Random();

static int[][] medium = {{2677, 1}, {2678, 1}, {2679, 1}, {2680, 1}, {987, 1}, {985, 1}, {4153, 1}, {11256, 1}, {1305, 1}, {1377, 1}, {4587, 1}};
static int[] mediums = medium[RANDOM.nextInt(medium.length)];

player.getInventory().addItem(mediums[0], mediums[1]);

When I loot the chest, it gives me a random item from the array.  My problem is that if I loot the chest again, it gives me the same item over and over.  I'll get a different item if I restart the server.  But it will stick to that item.  How do I make it give me random item every time?

Share this post


Link to post
Share on other sites

5 answers to this question

Recommended Posts

  • 1
static int[] mediums = medium[RANDOM.nextInt(medium.length)];

This will only be called once.

Instead, remove the static modifier and before you add the item to the player, call

mediums = medium[RANDOM.nextInt(medium.length)];

 

Share this post


Link to post
Share on other sites
  • 0
46 minutes ago, Arix said:
static int[] mediums = medium[RANDOM.nextInt(medium.length)];

This will only be called once.

Instead, remove the static modifier and before you add the item to the player, call

mediums = medium[RANDOM.nextInt(medium.length)];

 

Thank you sir.  Works like a charm now.

Share this post


Link to post
Share on other sites
  • 0
On 11/8/2016 at 0:23 PM, Arix said:
static int[] mediums = medium[RANDOM.nextInt(medium.length)];

This will only be called once.

Instead, remove the static modifier and before you add the item to the player, call

mediums = medium[RANDOM.nextInt(medium.length)];

 

 

use length - 1, the array starts at 0 so it will count 1 over and if landed on the size will throw a null pointer. 

Share this post


Link to post
Share on other sites
  • 0
34 minutes ago, Teek said:

 

use length - 1, the array starts at 0 so it will count 1 over and if landed on the size will throw a null pointer. 

nextInt's upper bound is exclusive (so effectively length - 1)

Share this post


Link to post
Share on other sites
  • 0
10 hours ago, Arix said:

nextInt's upper bound is exclusive (so effectively length - 1)

 

Ahh, yes. I forgot about the use of nextInt.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×