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);
}
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.