Java 程式以生成 n 個不同的隨機數
對於不同的號碼,使用集合,因為它的所有實現都會刪除重複項 -
Set<Integer>set = new LinkedHashSet<Integer>();
現在,建立一個 Random 類物件 -
Random randNum = new Random();
現在使用 Random 類的 nextInt 生成 10 個不同的隨機數 -
while (set.size() < 10) { set.add(randNum.nextInt(10)+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() < 10) { set.add(randNum.nextInt(10)+1); } System.out.println("Distinct random numbers = "+set); } }
輸出
Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]
廣告