Requirements description:
◦Coding realizes the double-color ball function
◦Double -color ball rules choose 6 of 33 red balls and 1 of 16 blue balls ◦Use random numbers to randomly generate 6 red ball numbers within 1 to 33 without repetition basketball number
The following is the process of code implementation:
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();
}