我在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是我遇到问题的方法。如果用户第一次输入复制品,则下一个循环表示他们输入的任何内容都是重复的。感谢您的任何帮助。
答案 0 :(得分:1)
使用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.
}
}
}
答案 1 :(得分:1)
你可以试试这个最简单的形式,
public void getUserPicks(){
Scanner keyboard = new Scanner(System.in);
int userPicks = 0;
while (hs.size() < 5) {
System.out.println("Enter your 5 lucky numbers for the lottery: ");
userPicks = keyboard.nextInt();
if (userPicks < 10 && userPicks > 0) {
if(hs.add(userPicks)){ // it return true if Unique value enter otherwise duplicate won't entered
}else{
System.out.println("You put an invalid entry. No duplicates allowed"
+ " please start over. \n ");
}
}else{
System.out.println("Not a valid entry. "
+ "Make sure the number is between 1-9 "
+ "Enter your 5 numbers again \n");
}
}
System.out.println("User Entered Values : " + hs);
}