gpt4 book ai didi

java - 具有数组列表的彩票类,没有重复的数字并且不能超出范围

转载 作者:行者123 更新时间:2023-11-30 03:09:15 24 4
gpt4 key购买 nike

我正在上 Java 入门课。我对这种编程语言比较陌生。我必须制作一个彩票类,其中用户必须输入 1-9 之间的数字,并且不能重复。为此,我制作了一个数组列表。这是我到目前为止所拥有的:

public class Lottery {

private int lotteryNumber[] = new int[5];
private ArrayList<Integer> userLotteryPicks = new ArrayList<Integer>(5);

public Lottery() {

Random myRan = new Random();

for (int i = 0; i < lotteryNumber.length; i++) {
lotteryNumber[i] = myRan.nextInt(9) + 1;
for (int j = 0; j < i; j++) {
if ((lotteryNumber[i] == (lotteryNumber[j])) && (i != j)) {
i = 0;
}
}
}
}

public void getUserPicks() {

Scanner keyboard = new Scanner(System.in);

int userPicks = 0;

for (int i = 0; i < 5; i++) {
System.out.println("Enter your 5 lucky numbers for the lottery: ");
userPicks = keyboard.nextInt();

if (userPicks < 10 && userPicks > 0) {
userLotteryPicks.add(userPicks);
} else {
System.out.println("Not a valid entry. "
+ "Make sure the number is between 1-9 "
+ "Enter your 5 numbers again \n");
i = 0;
}
for (int j = 0; j < i; j++) {
if ((userLotteryPicks.get(i) == (userLotteryPicks.get(j))) && (i != j)) {
i = 0;
System.out.println("You put an invalid entry. No duplicates allowed"
+ " please start over. \n ");
}
}
}
}

getUserPicks 是我遇到问题的方法。如果用户第一次输入重复项,则下一个循环会说他们输入的任何内容都是重复项。感谢您的任何帮助。

最佳答案

使用HashSet代替ArrayList来存储数字。集合不允许重复。对于任何错误的输入,您无需重新开始。检查下面的代码。

// Change this initialization to Set instead of ArrayList
private Set<Integer> userLotteryPicks = new HashSet<Integer>(5);

public void getUserPicks() {
Scanner keyboard = new Scanner(System.in);
int userPicks = 0;
System.out.println("Enter your 5 lucky numbers for the lottery: ");
for (int i = 0; i < 5; i++) {
userPicks = keyboard.nextInt();

boolean unique = false;
if (userPicks < 10 && userPicks > 0) {
unique = userLotteryPicks.add(userPicks); //if duplicate, then it return false.
} else {
System.out.println("Not a valid entry. "
+ "Make sure the number is between 1-9.");
i--; // for wrong inputs, decrease the counter by again, instead of start over again.
continue;
}
if (!unique) {
System.out.println("You put an invalid entry. No duplicates allowed. Enter the number again.");
i--; // for wrong inputs, decrease the counter by again, instead of start over again.
}
}
}

关于java - 具有数组列表的彩票类,没有重复的数字并且不能超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com