需求说明:
◦ 编码实现双色球功能
◦ 双色球规则红球33选6,蓝球16选1
◦ 使用随机数在1到33内随机产生6个红球号码,不重复
◦ 从1到16间随机产生一个蓝球号码
以下是代码实现的过程:
public static void main(String[] args) {
// 定义中奖号码
String first = "28 17 20 18 29 30 10";
int count = 0;
while(true) {
count++;
String caipiao = buyCaiPiao();
System.out.println("本次购买的彩票号码:" + caipiao);
if(first.equals(caipiao)) {
break;
}
}
System.out.println("你买了彩票的次数:" + count);
}
/**
* 购买彩票方法
* @return 返回彩票号码
*/
private static String buyCaiPiao() {
// 1-33中产生6个红球
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= 6; i++) {
int red = (int)(Math.random() * 33 + 1);
if(sb.indexOf(red + "") < 0) {
sb.append(red + " ");
} else {
// 如果找到了,相当于本次白跑了,i--,下次继续跑
i--;
}
}
// 1-16产生1个蓝色球
int blue = (int)(Math.random() * 16 + 1);
sb.append(blue);
return sb.toString();
}