检查重复

时间:2014-04-17 16:44:03

标签: java

我正在尝试编写检查数组中重复数字的代码。如果数字在同一行内重复,则应生成另一个随机数来替换该数字。这是我的类/方法,旨在实现这一目标:

import java.util.*;

public class NoRepeats
{
    public static void clean(int ticks[][])
    {        
        for(int i = 0; i < ticks.length; i++)
        {
            for(int j = 0; j < ticks[0].length; j++)
            {
                nums[j] = ticks[i][j];   
            }
            for(int k = 0; k < nums.length; k++)
            {
                for(int count = k + 1; count < nums.length; count++)
                {
                    int othNums = nums[count];
                    while(true)
                    {
                        if(nums[k] == othNums)
                        {
                            System.out.print("\n\n Repeat:" + nums[k] + k + "  " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
                            nums[k] = 1 + rndm.nextInt(48);
                            for(int counter = count; counter < nums.length; counter++)
                            {
                                int othNums2 = nums[count];
                                if(nums[k] == othNums2)
                                {
                                    System.out.print("\n\n Repeat NUM2:" + nums[k] + "  " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
                                    nums[k] = 1 + rndm.nextInt(48);
                                }
                            }
                            for(int l = 0; l < k; l++)
                            {
                                int othNums3  = nums[l];
                                if(nums[k] == othNums3)
                                {
                                    System.out.print("\n\n RepeatNUM2: " + nums[k] + "  " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
                                    nums[k] = 1 + rndm.nextInt(48);
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    count++;
               }   
            }
            for(int q = 0; q < nums.length; q++)
            {
                ticks[i][q] = nums[q];
            }
            count = 0;
        }
    }
    public static int nums[] = new int[6];
    public static int count = 1;
    public static Random rndm = new Random();
    public static int numsMatched[] = new int[100];
}

出于某种原因,仍有比赛,我不知道为什么。谁能找到我做错了什么?

1 个答案:

答案 0 :(得分:1)

您将count递增两次,从而跳过条目:

for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
  int othNums = nums[count];
  while(true)
  {
    //snip
  }
  count++; //<- increment 2
}

问题可能源于这样一个事实:你有一个静态变量,它也被称为count,并且会被循环中定义的count遮蔽:

public static int count = 1;

因此,要么删除第二个增量,要么重命名其中一个变量。