0

I have recently started to learn programming in java and in the program below I'm trying to print distinct array elements Like e.G if an int arr[]={2,5,4,9,3,2,5,9,4} then I want to be able to get the numbers only once i.e., expected value 2 5 4 9 3 Below is my code to do this but I'm getting incorrect o/p My o/p: 2 5 4 9. Can anyone point me out what am I doing wrong

 package prac;

    public class RemoveDup {

        public static void main(String[] args) {

    int[] a={2,5,4,9,3,2,5,9,4};
    int n=a.length;
    for(int i=0;i<=n;i++){
        //System.out.print("In i"+i);
        for(int j=i+1;j<n;j++){
            //System.out.println("In j"+j);
            if(a[i]==a[j]){
                System.out.println(a[i]);
            }
        }

    }
        }

    }
javsadi
  • 49
  • 1
  • 8

1 Answers1

1

Re-inventing the wheel is a good Idea but not the most optimal one if you're beginning to learn a Language. You could, of course, add some debug statements to see what is being compared etc. etc., or step through your code using some IDE (Netbeans/ Eclipse) and that way you can see what is happening.

My suggestion : you should use a Set, insert all your elements into the Set, and it would not have any duplicates if you insert the same value twice.

For example :

    int[] a={2,5,4,9,3,2,5,9,4};
    int n=a.length;
    HashSet<Integer> myVals = new HashSet<Integer>();
    for(int val : a){
        myVals.add(val);
    }
    for(int val : myVals){
        System.out.println(val);
    }
Exception_al
  • 1,049
  • 1
  • 11
  • 21