-1

How can I randomly choose a number from a list of given numbers in Java?

I have only these 5 numbers: 1000, 2000, 3000, 4000, 5000

Now I have to select any one number from this set of numbers randomly.

My code to try this

int ar[] = new int[4];
ar[0] = 1000;
ar[1] = 2000;
ar[2] = 3000;
ar[4] = 4000;

int randomArrayIndex = num.nextInt(ar.length);
Ry-
  • 218,210
  • 55
  • 464
  • 476
Ameer
  • 600
  • 1
  • 12
  • 27
  • 2
    What is `num`? And what is the result of your code (which is not complete I guess)? Please post a complete code that you have tried. – Rohit Jain Jan 31 '13 at 15:38
  • 2
    Given that `num` is an instance of the `Random` class, you're doing it quite right. What is _not_ working for you with this code? – Petr Janeček Jan 31 '13 at 15:40
  • 2
    @AudriusMeškauskas.. May be for you, and not for OP. – Rohit Jain Jan 31 '13 at 15:45
  • I'm assuming `ar[4]=4000;` should read `ar[3]=4000`, as index `4` does not exist (the _4th_ index does, but that is index **3**, because they start from 0). – Clockwork-Muse Jan 31 '13 at 16:39

3 Answers3

6
int randomArrayIndex = new Random().nextInt(ar.length); 
int number = ar[randomArrayIndex];
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
1

Try this

public static int myRandom(int low, int high) {
    return (int) (Math.random() * (high - low) + low);
}

and set low and high to 0 and 4.

Roman Holzner
  • 5,738
  • 2
  • 21
  • 32
1

If you don't want to repeat numbers from original array:

 Integer [] array = {1000,2000,3000,4000};
 Collections.shuffle(Arrays.asList(array));

If only one random number is required from the given array .

int[] array = {1000,2000,3000,4000};

int randomNumber = array[(int)(Math.random()*array.length)];
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39