import java.util.Arrays; import java.util.Scanner; //本题目来自Java核心卷(一)示例 public class TestStudent { public static void main(String[] args) { // 要想选择这样一个随机的数值集合,就要首先将数值 1, 2, …,n 存人数组 numbers 中: Scanner sc = new Scanner(System.in); System.out.println("最大抽到多少?"); int n = sc.nextInt(); System.out.println("你想抽几个数?"); int k = sc.nextInt(); // 总共个数集合 int[] numbers = new int[n]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i + 1; } // 抽取出的数的数组 int[] 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--; } Arrays.sort(result); System.out.println("你抽取的数字是:"); for (int ra : result) { System.out.print(ra + ","); } } }
原文地址:https://www.cnblogs.com/run-forrest-gump/p/12578491.html
时间: 2024-11-14 11:55:48