一、需求
1.随机生成一组中奖号码
2.用户输入一组双色球号码
3.判断中奖情况
4.中奖号码由6个红球(1-33)和1个蓝球(1-16)组成(6个红球不能重复)
二 ,代码
package lianxi;import java.util.Random;
import java.util.Scanner;public class Test11 {public static void main(String[] args) {//1.生成中奖号码int[] arr = creatNumber();System.out.println("===================");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();//2.用户输入彩票号码int[] userInputArr = userInputNumber();//3.判断用户的中奖情况//红球 蓝球int redCount = 0;int blueCount = 0;//判断红球for (int i = 0; i < userInputArr.length-1; i++) {int redNumber = userInputArr[i];for (int j = 0; j < arr.length - 1; j++) {if (redNumber == arr[j]) {redCount++;//如果找到了 那么后面的数字就没必要继续比较了//跳出内循环, 继续循环下一个红球号码是否中奖break;}}}//判断蓝球int blueNumber = userInputArr[userInputArr.length - 1];if (blueNumber == arr [arr.length - 1]) {blueCount++;}//根据红球的个数及蓝球的个数判断中奖情况if (redCount == 6 && blueCount == 1) {System.out.println("恭喜你 中奖1000万");} else if (redCount == 6 && blueCount == 0) {System.out.println("恭喜你 中奖500万");} else if (redCount == 5 && blueCount == 1) {System.out.println("恭喜你 中奖3000元");} else if ((redCount == 5 && blueCount == 0) || (redCount == 4 && blueCount == 1)) {System.out.println("恭喜你 中奖200元");} else if ((redCount == 4 && blueCount == 0) || (redCount == 3 && blueCount == 1)) {System.out.println("恭喜你 中奖10元");} else if ((redCount == 2 && blueCount == 1) || (redCount == 1 && blueCount == 1) || (redCount == 0 && blueCount == 1)) {System.out.println("恭喜你 中奖5元");} else {System.out.println("谢谢惠顾");}}public static int[] userInputNumber() {//1.创建数组用于添加购买的彩票号码//6个红球 1个蓝球 数组长度7int[] arr = new int[7];Scanner in = new Scanner(System.in);//输入红球号码for (int i = 0; i < 6; ) {System.out.print("请输入第" + (i + 1) + "个红球号码: ");int redNumber = in.nextInt();//redNumber 1~33 唯一不重复if (redNumber >= 1 && redNumber <= 33) {boolean flag = contains(arr, redNumber);if (!flag) {//不存在//有效的 可以添加到数组中arr[i] = redNumber;i++;} else {System.out.println("当前红球号码已经存在, 请重新输入");}} else {System.out.println("当前红球号码超出范围");}}//输入蓝球号码System.out.print("输入蓝球号码: ");//1-16while (true) {int blueNumber = in.nextInt();if (blueNumber >= 1 && blueNumber <= 16) {arr[arr.length - 1] = blueNumber;break;} else {System.out.println("当前蓝球号码超出范围");}}return arr;}public static int[] creatNumber() {//1.创建数组用于添加中奖号码//6个红球 1个蓝球 数组长度: 7int[] arr = new int[7];//2.随机生成号码并添加到数组当中//红球不能重复 1 2 3 4 5 6//蓝球 可以和红球号码重复//生成红球号码并添加到数组当中Random r = new Random();for (int i = 0; i < 6; ) {//获取红球号码int redNumber = r.nextInt(33) + 1;boolean flag = contains(arr, redNumber);if (!flag) {//把红球号码添加到数组当中arr[i] = redNumber;i++;}}//生成蓝球号码并添加到数组中int blueNumber = r.nextInt(16) + 1;arr[arr.length - 1] = blueNumber;return arr;}//用于判断数字在数组中是否存在private static boolean contains(int[] arr, int number) {for (int i = 0; i < arr.length; i++) {if (arr[i] == number) {return true;}}return false;}}
三 ,运行结果