Reputation: 27
I already know how to generate a random number within a range; but my question is about possibility of generating a number from a set of 2 or more specified numbers. for example: the output must be randomly chosen between exactly "1" or "3" or "100"
Another way to put it is: The value obtained will be any of the three numbers: 1, 3 or 100 (without any of the numbers in between).
Upvotes: 1
Views: 5462
Reputation: 5087
Java Math.random()
generates random numbers between 0.0 and 1.0 you can write a code for what you want.
For example:
double random = new Math.random();
random = myRandom(random);
public double myRandom(double random){
if(random < 0.33){return 1;}
else if(random < 0.66) {return 3;}
else {return 100;}
}
Upvotes: 0
Reputation: 28548
Random
is your solution for it:
public static int generateRandomNumber(int[] availableCollection) {
Random rand = new Random();
return availableCollection[rand.nextInt(availableCollection.length)];
}
Upvotes: 1
Reputation: 1733
{1,3,100}
Store them in an array and then select a random element from there. To select random element, see this: http://answers.yahoo.com/question/index?qid=20081025124826AAR8rmY
Upvotes: 0
Reputation: 168825
int[3]
..is one of many ways.
Upvotes: 6