模拟彩票摇号游戏
为了方便理解,特在此代码中添加了大量注释,其中有部分注释可有可无仅仅作为知识的回顾和扩展,熟练的可以忽略。
代码全文如下:
package day20181105;
import java.util.Arrays;
/**
* 模拟彩票摇号游戏
* @authorAdminsterator
*/
public class BallsDemo {
public static void main(String[] args) {
//设置奖池,存放摇奖号码
String[]pools={"01","02","03","04","05","06","07","08","09"
,"10","11","12","13","14","15","16","17","18","19"
,"20","21","22","23","24","25","26","27","28","29"
,"30","31","32"};
//定义boolean数组确定是否号码用过
boolean[]used=new boolean[pools.length];
//设置红球摇奖号
String[]redBalls=new String[6];
//定义随机抽出的摇奖号
int count=0;
while(true){
//random随机数后的‘*’号是定义不能超过这个数,且是从‘0’开始
int index=(int)(Math.random()*pools.length);
if(used[index]){
//Boolean类型定义的数据默认为false
continue;
}
redBalls[count++]=pools[index];
//使用过的号码定义为true
used[index]=true;
if(count==6){
break;
}
}
//为了美观sort排序
Arrays.sort(redBalls);
System.out.println("红球:"+Arrays.toString(redBalls));
redBalls=Arrays.copyOf(redBalls, redBalls.length+1);
//设置随机特码
redBalls[redBalls.length-1]=pools[(int)(Math.random()*7)];
System.out.println("蓝球:["+redBalls[redBalls.length-1]+"]");
System.out.println("本期中奖号码为:"+Arrays.toString(redBalls));
}
}
使用后的效果图:
如有不足请不吝赐教!