java模拟彩票中的36选7玩法
时间: 2023-11-22 15:56:56 浏览: 147
好的,以下是一个简单的 Java 程序,用于模拟彩票中的 36 选 7 玩法:
```java
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int[] lotteryNumbers = generateLotteryNumbers();
System.out.println("本期彩票中奖号码为:" + Arrays.toString(lotteryNumbers));
int[] userNumbers = getUserNumbers();
System.out.println("您选择的号码为:" + Arrays.toString(userNumbers));
int matchedCount = countMatchedNumbers(lotteryNumbers, userNumbers);
System.out.println("您中了 " + matchedCount + " 个号码。");
if (matchedCount == 7) {
System.out.println("恭喜您中了一等奖!");
} else if (matchedCount == 6) {
System.out.println("恭喜您中了二等奖!");
} else if (matchedCount == 5) {
System.out.println("恭喜您中了三等奖!");
} else if (matchedCount == 4) {
System.out.println("恭喜您中了四等奖!");
} else {
System.out.println("很遗憾,您没有中奖。");
}
}
// 生成彩票中奖号码
private static int[] generateLotteryNumbers() {
int[] lotteryNumbers = new int[7];
Random random = new Random();
for (int i = 0; i < lotteryNumbers.length; i++) {
int number;
do {
number = random.nextInt(36) + 1;
} while (contains(lotteryNumbers, number));
lotteryNumbers[i] = number;
}
Arrays.sort(lotteryNumbers);
return lotteryNumbers;
}
// 判断数组中是否包含某个元素
private static boolean contains(int[] array, int element) {
for (int i : array) {
if (i == element) {
return true;
}
}
return false;
}
// 获取用户选择的号码
private static int[] getUserNumbers() {
Scanner scanner = new Scanner(System.in);
int[] userNumbers = new int[7];
System.out.println("请输入您选择的号码(1-36之间的整数):");
for (int i = 0; i < userNumbers.length; i++) {
System.out.print("第" + (i + 1) + "个号码:");
int number;
do {
number = scanner.nextInt();
} while (number < 1 || number > 36 || contains(userNumbers, number));
userNumbers[i] = number;
}
Arrays.sort(userNumbers);
return userNumbers;
}
// 计算中奖号码个数
private static int countMatchedNumbers(int[] lotteryNumbers, int[] userNumbers) {
int count = 0;
for (int i : userNumbers) {
if (contains(lotteryNumbers, i)) {
count++;
}
}
return count;
}
}
```
运行程序后,会提示用户输入 7 个号码,然后随机生成彩票中奖号码,并计算用户选择的号码中有多少个与中奖号码相同。最后,根据中奖号码个数,给出相应的中奖提示。
阅读全文