用JAVA写出)1~30个数字,每次选择6个数字算为一注,每次最多可以选择5注
时间: 2023-06-25 13:05:40 浏览: 97
以下是用 Java 实现的代码:
```java
import java.util.*;
public class LotteryGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[30];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}
int maxTickets = 5;
int ticketCount = 0;
while (ticketCount < maxTickets) {
System.out.print("Please choose 6 numbers (1-30) separated by spaces: ");
int[] chosenNumbers = new int[6];
for (int i = 0; i < chosenNumbers.length; i++) {
chosenNumbers[i] = input.nextInt();
}
if (isValid(chosenNumbers, numbers)) {
ticketCount++;
System.out.println("Your ticket " + ticketCount + ": " + Arrays.toString(chosenNumbers));
} else {
System.out.println("Invalid numbers, please try again.");
}
}
}
public static boolean isValid(int[] chosenNumbers, int[] numbers) {
if (chosenNumbers.length != 6) {
return false;
}
Set<Integer> set = new HashSet<>();
for (int num : chosenNumbers) {
if (num < 1 || num > 30) {
return false;
}
if (!set.add(num)) {
return false;
}
if (!contains(numbers, num)) {
return false;
}
}
return true;
}
public static boolean contains(int[] numbers, int num) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == num) {
numbers[i] = 0;
return true;
}
}
return false;
}
}
```
这个程序允许用户选择每注的6个数字,并且验证这些数字是否有效(即数字在1到30之间,没有重复,且在可用数字列表中存在)。如果数字无效,则要求用户重新输入。程序最多允许用户选择5注。一旦用户选择了有效的数字,就会生成一张彩票并打印出来。
阅读全文