Java 程式生成無重複的隨機數
對於 Java 中的隨機數,建立一個 Random 類物件 −
Random randNum = new Random();
現在,建立一個 HashSet 來獲取僅有的唯一元素(即沒有重複項)−
Set<Integer>set = new LinkedHashSet<Integer>();
使用 Random 類 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]
廣告