Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

write a program in java that accept n number of elements in an array then display only duplicate elements

write a program in java that accept n number of elements in an array then display only duplicate elements
for example if we enter 12352342678898
it will show 238
i have tryed this but this is very long

import java.util.*;
class JavaApplication1 {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter Size: ");
    int s=sc.nextInt();
    int a[]=new int[s];
    int t[]=new int[s];
    int p=0;
    System.out.println("Enter numbers :-");
    for(int i=0;i<s;i++)
    {
        a[i]=sc.nextInt();
    }
    for(int i=0;i<s;i++)
    {
        boolean flag=false;
        for(int j=i+1;j<s;j++)
        {
            if(a[i]==a[j])
            {
                flag=true;
                break;
            }
        }
        if(flag==true)
        {
            t[p]=a[i];p++;
        }
    }
    System.out.print("duplicate elements are:- ");
    for(int i=0;i<p;i++)
    {
        boolean flag=false;
        for(int j=i+1;j<s;j++)
        {
            if(t[i]==t[j])
            {
                flag=true;
                break;
            }
        }
        if(flag==false)
        {
            System.out.print(t[i]+" ");
        }
    }
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One possibility is to sort the array a, e.g., using java.util.Arrays.sort(a);. Then just iterate through a and check for repeating numbers. That part could look like this:

    Arrays.sort(a);
    Integer prev = null;
    Integer printed = null;
    for (int val : a) {
            if (prev != null && val == prev && (printed == null || val != printed)) {
                    System.out.print(val + " ");
                    printed = val;
            }
            prev = val;
    }

This is quite an ugly program and solution (my code). While this works from algorithmic point of view, I do not recommend this as a good programming practice. For instance, using null checks… It is also advisable to move the detection of duplicate numbers into separate method (or better, class), without printing out. This is mixing computation with user interface, bad practice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading