<pre>package com.springmvcmybatis.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.springmvcmybatis.Entity.WeightCategory;
public class WeightRandom {
static List<WeightCategory> categorys = new ArrayList<WeightCategory>();
private static Random random = new Random();
public void initData() {
WeightCategory wc1 = new WeightCategory("A",15);
WeightCategory wc2 = new WeightCategory("B",18);
WeightCategory wc3 = new WeightCategory("C",15);
WeightCategory wc4 = new WeightCategory("D",20);
WeightCategory wc5 = new WeightCategory("E",15);
WeightCategory wc6 = new WeightCategory("F",17);
categorys.add(wc1);
categorys.add(wc2);
categorys.add(wc3);
categorys.add(wc4);
categorys.add(wc5);
categorys.add(wc6);
}
public String Weight() {
initData();
Integer weightSum = 0;
for (WeightCategory wc : categorys) {
weightSum += wc.getWeight();
}
if (weightSum <= 0) {
System.err.println("Error: weightSum=" + weightSum.toString());
return null;
}
Integer n = random.nextInt(weightSum); // n in [0, weightSum)
Integer m = 0;
for (WeightCategory wc : categorys) {
if (m <= n && n < m + wc.getWeight()) {
System.out.println("随机数是 "+wc.getCategory());
return wc.getCategory();
}
m += wc.getWeight();
}
return null;
}
}
</pre>
代码片段: 根据权重产生随机数-WeightRandom.java
package com.springmvcmybatis.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.springmvcmybatis.Entity.WeightCategory;
publi...
- 发表于 2018-07-05 11:20
- 阅读 ( 708 )
- 分类:代码片段
你可能感兴趣的文章
- Java 添加条码、二维码到PDF文档 134 浏览
- Java 在Excel中添加筛选器并执行筛选 91 浏览
- JAVA + VUE + 简洁UI:分离式软件平台形成之旅 265 浏览
- Java 设置Word中的表格自适应的3种方式 113 浏览
- LeaRun快速开发平台,.net/java项目开发工具简析 142 浏览
- JVM学习笔记之类装载器-ClassLoader 203 浏览
随机文章
- 聊聊分布式事务,再说说解决方案 4864 浏览
- Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean. 4324 浏览
- Spring Boot源码分析——自动配置 3021 浏览
- No auto configuration classes found in META-IN F/spring.factories. If you are using a custom packaging, make sure that file is correct. 7957 浏览
- 修改spring Boot启动时的默认图案Banner 1515 浏览
相关问题
- java基础知识提问 1 回答
条评论
请先 登录 后评论
发送私信
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!