情景:
假如从50个数字中确定10个中奖号码。
中奖号码要从50个数字中随机产生,中奖号码不可以重复,并对中奖号码进行排序。
解题思路:
- 首先建立一个长度为n号码的号码库:
- 建立一个数组存放k个中奖号码
- 抽取k个中奖号码。Math.random方法将返回一个0到1之间(包含0、不包含1)的随机浮点数。用n乘以这个浮点数,就可以得到从0到n-1之间的一个随机数,将此数作为号码库的下标,取出号码库该下标的数放入中奖号码库。
- 确保不会再次抽到相同的数字,用数组最后一个数放到被抽到的位置上,并将n-1。
- 将中奖号码库排序并输出。
运行情况:
import java.util.Arrays;
import java.util.Scanner;/*** @author yy~* @version 1.0*/
public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("需要多少个中奖号码?");int k =scanner.nextInt();System.out.println("一共有多少个号码?");int n = scanner.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];n--;}Arrays.sort(result);System.out.println("中奖号码为:");for (int r: result) {System.out.print(r+"\t");}}
}