开发者

Duplicate Elimination in java

I need to write a program for someone to enter 5 numbers from 10 to 100 but I don't know how i can eliminate duplicates? Anybody got any bright ideas on how i can do开发者_StackOverflow it?


Add them into hashset, and check how many elements you have in set.

For example:

    Scanner sc = new Scanner(System.in);
    HashSet<Integer> nrs = new HashSet<Integer>();
    int n;

    System.out.println("Enter 5 numbers from 10 to 100");
    do {
        if (sc.hasNextInt())
            if ((n = sc.nextInt()) > 9 && n < 101)
                nrs.add(new Integer(n));
        System.out.println("We have numbers: " + nrs);
    } while (nrs.size() < 5);

    System.out.println("Superb. You entered numbers: " +nrs);


Use a Set implementation whic by definition does not contain duplicates...

TreeSet<Integer> ints = new TreeSet<Integer>();

int[] int_array = { 1, 2, 3, 4, 3, 5, 4, 2, 3, 4, 3 4, 2, 1 };

for (int n : int_arr)
   ints.add(n);

for (int n : ints)
  System.out.preintln(n);

outputs: 1 2 3 4 5


Keep track of numbers entered so far. If a user's input has been entered already ask the user to re-enter another number.


This is not as trivial as it seems.

But after a little while I came to this:

class ClearDup { 
    public static void main( String ... args ) { 
        int [] o = {1,2,1,3,1,2,4};
        int [] f = new int[o.length];

        int filterIndex = 0;
        original: for( int i : o ) { 
            for( int j : f ) { 
                if( i == j ) { 
                    continue original;
                }
            }
            f[filterIndex++] = i;
        }

        int [] result = java.util.Arrays.copyOf(f, filterIndex );
        System.out.println( java.util.Arrays.toString( result ) );
    }
}


class Aaaray{
    static int arr[]={1,2,3,4,2,3,4,3,5,6,4,4,1,6,7,3,8,7,9,10,3,10,11,11,12,1,2,5,13,14,12,14};
    static int brr[]= new int[8];

    public static void main(String[]args){

        for(int j=0;j<arr.length;j++){
            for(int i=j+1;i<arr.length;i++){
                if(arr[j] == arr[i]){
                    arr[i]=0;
                }
            }
        }

        for(int m=0;m<arr.length;m++){
            if(arr[m]!=0){
                int t =arr[m];
                System.out.println(t);
            }
        }
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜