zoukankan      html  css  js  c++  java
  • Java学习笔记(六)

    一、内容:做一个抽奖程序,可以设定参与抽奖的总人数和奖项的个数,获奖不可重复。
    二、方法:
    在 ArrayList List容器中顺序添加指定数量的整数(即设置总参与抽奖人数),用Random类产生随机数,抽完一等奖后用remove删除获得一等奖的号码,之后用Collections.shuffle()方法打乱顺序。
    三、代码:
    import java.util.*;

    public class Choujiang {
    private ArrayList List;
    private Random rand;

    public void deal(){
    //向 List容器中顺序添加指定数量的整数
    if(List == null){
    List = new ArrayList ();
    for(int i=1;i<=100;i++){
    List.add(i);
    }
    Collections.shuffle(List);
    return;
    }
    }

    public void draw(){
    //产生随机数
    rand = new Random();

    //获得一等奖的号码数
    int s = rand.nextInt(List.size());
    System.out.println("恭喜" + List.get(s) + "号获得一等奖!");
    //删除List中获得一等奖的号码
    List.remove(s);
    //打乱List中的号码顺序
    Collections.shuffle(List);
    
    //获得二等奖的号码数
    for(int i=0;i<2;i++){
    	int s2 = rand.nextInt(List.size());
    	System.out.println("恭喜" + List.get(s2) + "号获得二等奖!");
    	List.remove(s2);
    }
    Collections.shuffle(List);
    
    //获得三等奖的号码数
    for(int i=0;i<3;i++){
    	int s3 = rand.nextInt(List.size());
    	System.out.println("恭喜" + List.get(s3) + "号获得三等奖!");
    	List.remove(s3);
    }
    Collections.shuffle(List);
    

    }

    public static void main(String[] args) {
    	// TODO Auto-generated method stub
    	Choujiang cj = new Choujiang();
    	cj.deal();
    	cj.draw();
    }
    

    }
    四、程序运行图:

  • 相关阅读:
    装饰器
    函数对象与闭包
    名称空间与作用域
    函数的参数
    函数的基本使用
    ${}与#{}的区别
    thymeleaf之日期格式化
    template might not exist or might not be accessible by any of the configured Template Resolvers
    springboot使用@Scheduled之cron表达式详解
    自定义springboot项目启动图案
  • 原文地址:https://www.cnblogs.com/mijx/p/5486080.html
Copyright © 2011-2022 走看看