彩票问题(lottery drawing)

该博客介绍了一个Java程序,用于模拟彩票抽奖过程。程序首先从用户输入的最高数值中生成一个包含所有可能数字的数组,然后随机抽取指定数量的数字,并确保每次抽取后将已选数字移出剩余选择池,最后输出排序后的彩票号码组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. import java.util.Arrays;
  2. import java.util.Scanner;


  3. public class LotteryDrawing {

  4.     /**
  5.      * @param args
  6.      */
  7.     public static void main(String[] args) {
  8.         // TODO Auto-generated method stub
  9.         Scanner in = new Scanner(System.in);
  10.         System.out.println("How many numbers do you need to draw?");
  11.         int k = in.nextInt();
  12.         
  13.         System.out.println("What is the heigh number you can draw?");
  14.         int n = in.nextInt();
  15.         
  16.         //fill an array with numbers 1,2,3...n
  17.         int[] numbers = new int[n];
  18.         for (int i = 0; i < numbers.length; i++) {
  19.             numbers[i] = i + 1;
  20.         }
  21.         
  22.         //draw k numbers and put them into a second array
  23.         int[] result = new int[k];
  24.         for (int i = 0; i < result.length; i++) {
  25.             //make a random index between 0 and n-1
  26.             int r = (int)(Math.random() * n);
  27.             
  28.             //pick the element at the random location
  29.             result[i] = numbers[r];
  30.             
  31.             //move the last element into random location,很巧妙的替换方法,把最后一个数替换到已选出数的位置,数组上限  再减一
  32.             numbers[r] = numbers[n-1];
  33.             n--;
  34.         }
  35.         
  36.         // print the sorted array,数组排序简单排序方法,顺序排序
  37.         Arrays.sort(result);
  38.         System.out.println("Bet the following combination. It'll make you rich!");
  39.         for(int r : result) {
  40.             System.out.println(r);
  41.         }
  42.     }

  43. }
摘自core java第七版

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值