我是自学Java,而且我被困在一个简单的项目上。我希望收到6个独特的'彩票'来自用户的数字。
到目前为止,我只有:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
任何帮助表示赞赏!!
答案 0 :(得分:3)
尝试并保持逻辑简单。
例如......
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
有了这个,只有一点可以提示用户。其他所有内容都用于控制元素位置(i
)以满足您的要求。
现在,我确信还有其他方法可以做到这一点,这只是一个简单的例子;)
答案 1 :(得分:0)
移动数字外部循环的请求,当数字数组上的数字循环找到匹配时。如果找到匹配重新询问数字(在用于查找匹配的for循环之外),否则如果找不到匹配,则将数字添加到数组。
答案 2 :(得分:0)
你认为你的for循环并不复杂。无论如何,你可以试试这个:
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}