ajax无刷新调用抽奖程序:
PrintWriter out = null;
try {
response.setCharacterEncoding("UTF-8");//这种方法可以
out = response.getWriter();
StringBuilder outString = new StringBuilder();
Object result[] = award(prizeArr);//抽奖后返回ID和奖品信息
System.out.println("\t奖项ID:"+result[0]+"\t提示信息:"+result[1]);
//此处书写逻辑代码
outString.append(result[0]+","+result[1]);
out.print(outString);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
out.flush();
out.close();
}
}
//抽奖并返回奖项
public Object[] award(Object[][] prizeArr){
//概率数组
Integer obj[] = new Integer[prizeArr.length];
for(int i=0;i<prizeArr.length;i++){
obj[i] = (Integer) prizeArr[i][2];
}
Integer prizeId = getRand(obj); //根据概率获取奖项id
String msg = "";
if(prizeId != null){
msg = (String) prizeArr[prizeId][1];//提示信息
return new Object[]{prizeId,msg};
}else{
msg = "您的抽奖次数已用尽!";
return new Object[]{"",msg};
}
}
//根据概率获取奖项
public Integer getRand(Integer obj[]){
Integer result = null;
try {
int sum = 0;//概率数组的总概率精度
for(int i=0;i<obj.length;i++){
sum+=obj[i];
}
for(int i=0;i<obj.length;i++){//概率数组循环
int randomNum = new Random().nextInt(sum);//随机生成1到sum的整数
if(randomNum<obj[i]){//中奖
result = i;
break;
}else{
sum -=obj[i];
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}