//写一个生成彩票号码的小程序,[1,33]之间(包含1和33)随机选七个不重复的数字 //并把生成的彩票号码打印在控制台上。 //解析用到的知识点有: //数组 //生成随机数 //循环语句 //条件判断语句(注:7个数字不能重复)Java
时间: 2023-09-08 12:13:56 浏览: 154
好的,以下是Java语言实现生成彩票号码的小程序:
```java
import java.util.Arrays;
import java.util.Random;
public class LotteryNumberGenerator {
public static void main(String[] args) {
int[] lotteryNumbers = new int[7]; // 定义一个长度为7的数组用于存储彩票号码
Random random = new Random(); // 创建一个随机数生成器
for (int i = 0; i < lotteryNumbers.length; i++) {
int num = random.nextInt(33) + 1; // 生成1-33之间的随机数
while (contains(lotteryNumbers, num)) { // 如果随机数已经存在于数组中,则重新生成
num = random.nextInt(33) + 1;
}
lotteryNumbers[i] = num; // 将生成的不重复的随机数存入数组
}
Arrays.sort(lotteryNumbers); // 对数组进行排序
System.out.print("彩票号码为:");
for (int num : lotteryNumbers) {
System.out.print(num + " ");
}
}
// 判断数组中是否包含指定的数字
private static boolean contains(int[] arr, int num) {
for (int i : arr) {
if (i == num) {
return true;
}
}
return false;
}
}
```
程序运行时,会生成长度为7的随机不重复的数字数组,并将其排序后打印在控制台上,例如:
```
彩票号码为:2 9 11 12 21 27 31
```