Java实现抽奖功能(简单易懂的抽奖模板)盲盒抽奖都可以套用上

entity

public class Goods {
    public Goods(String name, int wight) {
        this.name = name;
        this.wight = wight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getWight() {
        return wight;
    }

    public void setWight(int wight) {
        this.wight = wight;
    }

    private String name; //商品名
    private int wight ; //权重
}

VO

public class Container {
    public Container(String name, int num) {
        this.name = name;
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    //    容器
    private String name;
    private int num;//抽奖会用上

}

实现类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public  class Lottery {
    public static String draw(){
//        列出商品
        Goods goods1 =new Goods("洗洁精",20);
        Goods goods2 =new Goods("大米",10);
        Goods goods3 =new Goods("火彩盒",5);
        Goods goods4 =new Goods("lv包包",15);
        Goods goods5 =new Goods("macbook",22);
        Goods goods6 =new Goods("ipadpro2020",24);
        Goods goods7 =new Goods("火影忍者全套漫画集",4);
//        开始抽奖

        int sum=0;//总数
        int n=0 ;//用于抽奖
        int a1=0;
        int a2=0;
        List containers =new ArrayList<>();

        containers.add(new Container(goods1.getName(),sum+=goods1.getWight()));
        containers.add(new Container(goods2.getName(),sum+=goods2.getWight()));
        containers.add(new Container(goods3.getName(),sum+=goods3.getWight()));
        containers.add(new Container(goods4.getName(),sum+=goods4.getWight()));
        containers.add(new Container(goods5.getName(),sum+=goods5.getWight()));
        containers.add(new Container(goods6.getName(),sum+=goods6.getWight()));
        containers.add(new Container(goods7.getName(),sum+=goods7.getWight()));

        int num =(int)(Math.random()*sum+1); //1到权重总和的一个随机数字

        for(int i=0;i=a1&&num

你可能感兴趣的:(java,后端,java-ee,spring,boot,spring)