对于Java中的随机数,请创建一个Random类对象-
Random randNum = new Random();
现在,创建一个HashSet以仅获取唯一元素,即不重复-
Set<Integer>set = new LinkedHashSet<Integer>();
使用随机类nextInt生成随机数-
while (set.size() < 5) { set.add(randNum.nextInt(5)+1); }
import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; public class Demo { public static void main(final String[] args) throws Exception { Random randNum = new Random(); Set<Integer>set = new LinkedHashSet<Integer>(); while (set.size() < 5) { set.add(randNum.nextInt(5)+1); } System.out.println("Random numbers with no duplicates = "+set); } }
输出结果
Random numbers with no duplicates = [2, 4, 1, 3, 5]