检查重复的用户输入数组值时出错

时间:2014-08-27 04:53:40

标签: java arrays duplicates

我是自学Java,而且我被困在一个简单的项目上。我希望收到6个独特的'彩票'来自用户的数字。

  1. 将要求用户输入一个整数。
  2. 每个用户输入都将放入一个数组中。
  3. 如果用户输入先前输入的号码,我想提示再次重新输入该号码。
  4. 重新检查新输入。如果是唯一的,请继续for循环。如果不是唯一的,请再次运行第3步。
  5. 到目前为止,我只有:

    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();
                }
            }
        }
    }   
    

    任何帮助表示赞赏!!

3 个答案:

答案 0 :(得分:3)

尝试并保持逻辑简单。

  • 虽然用户未输入6个号码,但循环
  • 向用户询问值
  • 检查是否重复
  • 如果是,请要求用户重新输入值
  • 如果不是(重复)将计数器递增到下一个元素......

例如......

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();
        }
    }