java 无重复取随机数

来源:互联网 发布:湖南工程造价软件 编辑:程序博客网 时间:2024/05/17 03:51
Scanner in = new Scanner(System.in);System.out.println("How many numbers do you need to draw?");int k = in.nextInt();System.out.println("What is the highest number you can draw?");int n = in.nextInt();int numbers[] = new int[n];// n=5,k=6// fill an array with numers 1,2,3...nfor (int i = 0; i < numbers.length; i++) {numbers[i] = i + 1;}// draw k numbers and put them into a second arrayint[] result = new int[k];for (int i = 0; i < result.length; i++) {int r = (int) (Math.random() * n);result[i] = numbers[r];numbers[r] = numbers[n - 1];n--;}// print the sorted arrayArrays.sort(result);System.out.println("Bet the following combinaation.It'll make you rich!");for (int r : result)System.out.println(r);
0 0
原创粉丝点击