'User inputs specific set of number and random number from the set is outputted
I have a java code that randomizes a number from a specific set, i want to be able to have the user inputs the specific set such as: {1,6,400,500} and the output is randomized from these numbers, how would i do that?, here is the code i have:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class Randomizer {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(24);
list.add(77);
list.add(90);
list.add(80);
list.add(1790);
Randomizer obj = new Randomizer();
int boundIndex = 3;
System.out.println(
obj.getRandomElement(list, boundIndex));
}
public int getRandomElement(List<Integer> list,
int bound)
{
return list.get(
ThreadLocalRandom.current().nextInt(list.size())
% bound);
}
}
Solution 1:[1]
You can use the Random java util:
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(24);
list.add(77);
list.add(90);
list.add(80);
list.add(1790);
Random random = new Random();
int randomInt = list.get(random.nextInt(list.size()));
System.out.println("Random int from list = " + randomInt);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ruggierin |
