I need a float
or integer
, not exactly generated but picked randomly.
Do I need to use and import math.random class
?
For example I have 3 integers : 1, 6 and 3. I want one of them to be picked randomly.
If you want each of your three values, but in a random order, then you might put them in an array. And, shuffle that array, you might use Arrays.asList(T...)
and Collections.shuffle(List)
. Next, iterate the values in the array (perhaps with a for-each
loop). Something like
public static void main(String[] args) {
Integer[] arr = new Integer[] { 1, 6, 3 };
Collections.shuffle(Arrays.asList(arr));
for (int i : arr) {
System.out.println(i);
}
}
But, if you really need to pick just one random value at a time (say 10 times) then you could use a Random
and nextInt(int)
and a for
loop. That might look something like
public static void main(String[] args) {
int[] arr = new int[] { 1, 6, 3 };
Random rand = new Random();
for (int i = 0; i < 10; i++) {
int index = rand.nextInt(arr.length);
System.out.println(arr[index]);
}
}
You have to create an array with the values that you want to get randomly. Like this:
int [] values = {1,3,6};
And you never have to forget to put:
Random rand = new Random();
Because if you don't put it, the Random function won't works properly.
So, then now you can access to your value randomly, like this:
int numObtained = rand.nextInt((values.length - 0) + 1) + 0;
The final code will be:
int [] values = {1,3,6};
Random rand = new Random();
int numObtained = rand.nextInt((values.length - 0) + 1) + 0;
I expect it helps to you!
Generate a random index from the numbers you want and then take the number from the
array