这段代码有什么问题?

时间:2011-08-12 15:23:13

标签: java arrays duplicates

我编写了这个来尝试在数组中找到重复项并在每次找到重复元素时递增计数,这个程序可以工作但是如果我在if语句后面放了一个else语句,编译器会打印出else语句,即使数组有重复的元素......

  public class arraysexpmnt {
  public static void main(String[] args) {
    int[] arr={2,2,2,5,7,8,9,9,8,7};
    int count=0;
    for(int i=0;i<arr.length;i++){
        for(int j=i+1;j<arr.length;j++){
            if(arr[j]==arr[i]){
                count++;
                 System.out.println("Duplicate found! Original is " + arr[i] + " and match is " +arr[j]+" and the count of similar elements is "+count);
            }

        }

    }


}

}

4 个答案:

答案 0 :(得分:1)

只要在循环中数组中的两个元素不匹配,就会执行else子句。这是很常见的事情。在那里放置相同的跟踪println,你会看到它。

答案 1 :(得分:1)

我认为你要寻找的代码是:

  public class arraysexpmnt {

     public static void main(String[] args) {
       int[] arr={2,2,2,5,7,8,9,9,8,7};
       int count=0;
       for(int i=0;i<arr.length;i++){
          boolean found = False;
          for(int j=i+1;j<arr.length;j++){
             if(arr[j]==arr[i]){
                count++;
                System.out.println("Duplicate found! Original is " + arr[i] + " and match is " +arr[j]+" and the count of similar elements is "+count);
                found = True;
             }
           }
           if (!found) {
                System.out.println("No duplicate found for  Original: " + arr[i] );
           }
        }

     }
  }

答案 2 :(得分:0)

代码看起来很好。如果你的代码在当前循环中没有找到重复的元素,它应该像你说的那样执行else子句。如果这不是您想要的功能,那么您必须更改逻辑。您希望代码执行什么操作?

答案 3 :(得分:0)

您的代码输出:

Duplicate found! Original is 2 and match is 2 and the count of similar elements is 1 
Duplicate found! Original is 2 and match is 2 and the count of similar elements is 2
Duplicate found! Original is 2 and match is 2 and the count of similar elements is 3
Duplicate found! Original is 7 and match is 7 and the count of similar elements is 4
Duplicate found! Original is 8 and match is 8 and the count of similar elements is 5
Duplicate found! Original is 9 and match is 9 and the count of similar elements is 6

如果您的数组已经排序,那么只要找到匹配的j,就可以增加i。这将阻止超过3种情况的额外报告。您可能还希望重置每次i次迭代的计数。

但是,您的数组并未完全排序。如果你想消除重复,可能需要另一种方法。