我有一个java代码,它可以随机化特定集合中的数字,我希望能够让用户输入特定集合,例如:{1,6400500},并且输出是从这些数字中随机化的,我该怎么做?,这是我的代码:
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);
}
}
您可以使用Random javautil:
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);
}