所用知识点
- 变量
- 数组
- 简单方法
- if语句
- while循环
- switch语句
- for循环
- Random 随机数
- Scanner 输入
代码
import java.util.Random;
import java.util.Scanner;
public class HomeWork7_1 {
public static void main(String[] args) {
//双色球
//数组的最后一个为蓝色球
int[] ballArr = new int[7]; //生成双色球数组
int[] youArr = new int[7]; //生成你号码的数组
Scanner sc = new Scanner(System.in);
for (int i = 0 ;i<7;i++) {
System.out.println("请输入号码");
var youNum =sc.nextInt();//输入号码
while (valueDetection(youNum)) { //判断数字在不在1-100之间
youNum =sc.nextInt();
}
youArr[i]=youNum;
while (duplicateDetection(youArr,i)) { //判断是否重复输入
System.out.println("输入重复,请重新输入");
youArr[i]=sc.nextInt();
}
}
ballArr = towColorBall();
//打印双色球本期号码
for (int i = 0; i < 7; i++) {
System.out.printf("%02d ",ballArr[i]);
}
System.out.println();
//判断奖项
if (youArr[6]==ballArr[6]) {//判断蓝色球(也就是数组的最后一个)
switch (winDetection(ballArr, youArr)+1) { //+1 需要红色球相同个数 加上蓝色球的数(也就是数组最后一个)
case 7: System.out.println("恭喜获得一等奖!"); break;
case 6: System.out.println("恭喜获得三等奖!"); break;
case 5: System.out.println("恭喜获得四等奖!"); break;
case 4: System.out.println("恭喜获得五等奖!"); break;
case 3:
case 2:
case 1: System.out.println("恭喜获得六等奖!"); break;
}
}else {
switch (winDetection(ballArr, youArr)) {
case 6: System.out.println("恭喜获得二等奖!"); break;
case 5: System.out.println("恭喜获得四等奖!"); break;
case 4: System.out.println("恭喜获得五等奖!"); break;
case 0: System.out.println("很遗憾没有获奖"); break;
}
}
}
//刷色球生成
public static int[] towColorBall() {
Random sj = new Random();
int[] re = new int[7];
for (int i = 0; i < 7; i++) {
re[i] = sj.nextInt(100); // [0,100) 调试的时候可以去掉一个零。比较容易中奖。
while (duplicateDetection(re, i)) {
re[i] = sj.nextInt(100);
}
}
return re;
}
//双色球生成重复判断
public static boolean duplicateDetection(int[] Red, int j) {
boolean index = false;
for (int i = j - 1; i >= 0; i--) {
if (Red[j] == Red[i]) {
index = true;
}
}
return index;
}
public static int winDetection(int[] array1, int[] array2) {
int num = 0;
for (int i = 0; i < array1.length-1; i++) { //将每个数组的最后一个蓝色球去掉 只判断红色球
for (int j = 0; j < array2.length-1; j++) {
if (array1[i] == array2[j]) {
num++;
}
}
}
return num;
}
public static boolean valueDetection(int num) {
boolean swi = false;
if (num<0||num>=100) {
System.out.println("输入错误,请输入0-99之间的数");
swi = true;
}
return swi;
}
}
结语
有什么可以优化的评论交流。大家一起进步~