白天玩的时候发现creatLottery()中避免重复数部分并不能真的避免重复 所以改进了下代码如下:
- import java.util.Scanner;
- class Game {
- public static void main(String[] args) {
- int[] arr = buy(); //购买彩票
- int[] brr = creatLottery(); //开奖
- int x = compare(arr,brr); //比较购买的彩票和开奖的号码
- contrastNumber(x); //兑奖
- }
- public static int[] buy() { //定义一个方法buy 卖彩票
- int[] arr = new int[5]; //创建一个数组用于存储手购买的彩票号码
- for (int i=1;i<=5 ;i++ ) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入您想购买的号码:");
- arr[i-1] = sc.nextInt();
-
- }
- System.out.println("您购买的彩票是:");
- print(arr);
- return arr;
- }
- public static void print(int[] arr){ //定义方法print用于打印 数组
- for (int i = 0;i < arr.length ;i++ ) {
- System.out.print(arr[i]+",");
- }
- }
- public static int[] creatLottery(){ //定义 方法creatLottery()生成彩票
- int[] arr = new int[5];
- int i = 0;
- w: while (true) { //避免重复数的出现
- int num=(int)(Math.random()*12)+1;
- if (indexOf(arr,num)) {
- continue w;
- }else
- arr[i]=num;
- i++;
- if(i==arr.length)
- break;
- }
- System.out.println("\n"+"本期12选5的中奖号码是:");
- System.out.println();
- print(arr);
- return arr;
- }
- public static boolean indexOf(int[] arr,int x) {//判断数组arr中是否有x;
- for (int i = 0;i<arr.length ;i++) {
- if (arr[i] == x) {
- return true;
- }
- }
- return false;
- }
-
-
-
- public static void contrastNumber(int sum){//定义方法contrastNumber()判断是否中奖
- switch (sum) {
- case 0:
- System.out.println("倒霉蛋,一个号码都没中");
- break;
- case 1:
- System.out.println("做好事不留名捐献2元钱");
- break;
- case 2:
- System.out.println("二狗,汪汪汪汪汪汪 20块");
- break;
-
- case 3:
- System.out.println("三等奖,10000赚了一笔");
- break;
- case 4:
- System.out.println("二等奖,200w报警了");
- break;
- case 5:
- System.out.println("一等奖,500w运气用光了以后买彩票也中不了了");
- break;
-
- }
- }
- public static int compare(int[] arr,int[] brr){//比较数组中相同元素的个数
- int sum = 0;
- for (int i=0;i < arr.length ;i++ ) {
- for (int j=0;j < brr.length ;j++ ) {
- if (arr[i] == brr[j]) {
- sum ++;
- arr[i]= -1; // -1 ,-2 都是flag用于去掉重复项
- brr[j]= -2;
- //System.out.println(arr[i]);
- break;
- }
- }
- }
- System.out.println("\n"+sum);
- return sum;
- }
- }
-
复制代码 |