package randomT;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class TestMathRandom
{
//方法名称
String method_Name;
//Test
public static void main(String[] args)
{
new TestMathRandom().test();
}
private void test()
{
int [] a = new int[10000];
//方法一测试
showR1(a);
//方法二测试
showR2(a);
//方法三测试
showR3(a);
}
//1生产随机数 Random
private void showR1(int [] a)
{
setName("showR1方法:");
Random r = new Random();
for(int k=0;k<10000;k++)
{
int i = r.nextInt(10);
a[k] = i;
}
countEveryNum(a);
}
//2生产随机数Math.random()
private void showR2(int [] a)
{
setName("showR2方法:");
for(int k=0;k<10000;k++)
{
double aa = Math.random() * 10;
a[k] = (int) aa;
}
countEveryNum(a);
}
//3可控概率生产随机数
private void showR3(int [] a)
{
setName("showR3方法:");
Random r = new Random();
for(int k=0;k<10000;k++)
{
int caseI = r.nextInt(100);
if(caseI <= 10)
{
a[k] = 9;
}
if(caseI >10 &&caseI <= 20)
{
a[k] = 8;
}
if(caseI >20 &&caseI <= 30)
{
a[k] = 7;
}
if(caseI >30 &&caseI <= 40)
{
a[k] = 6;
}
if(caseI >40 &&caseI <= 50)
{
a[k] = 5;
}
if(caseI >50 &&caseI <= 60)
{
a[k] = 4;
}
if(caseI >60 &&caseI <= 70)
{
a[k] = 3;
}
if(caseI >70 &&caseI <= 80)
{
a[k] = 2;
}
if(caseI >80 && caseI <= 81)
{
a[k] = 1;
}
if(caseI >90 && caseI <= 100)
{
a[k] = 0;
}
}
countEveryNum(a);
}
//统计每个数字出现的次数
private void countEveryNum(int [] a)
{
Map map = new HashMap();
//统计数字出现的次数
int count = 0;
int k=1;
for(int i=0;i<a.length;i++)
{
if(map.containsKey(a[i]))
{
int value_key = (Integer) map.get(a[i]);
int old = map.size();
map.put(a[i],value_key);
int new_count = map.size();
if(new_count == old)
{
map.put(a[i],value_key+=1);
}
}
else
{
map.put(a[i],1);
}
}
System.out.println(method_Name+"---map:"+map.entrySet());
}
private void setName(String name)
{
this.method_Name = name;
}
}
原文地址:https://www.cnblogs.com/zssw1990/p/9220130.html