Pages

Thursday, September 12, 2013

How to remove duplicates in an array using java without using function?

Here's a simple code for removing duplicates in String array without using function or methods. I hope this would helps.



import java.io.*;
public class Arrayremoveduplicates {

    public static void main(String[] args) throws Exception {
   
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader scan = new BufferedReader (reader);
   
        String [] name = new String[5];
       
        System.out.println("Enter name: ");
        for (int i=0;i<name.length;i++)
        {
         
          name[i] = scan.readLine();
    }
      System.out.println("List of 5 Names :");
   for (int a = 0; a < name.length; a++)
   {
        System.out.print(name[a] + " ");
   }
        System.out.println();
        int total=0;
        System.out.println("Names without duplicates :");
        for (int i = 0; i < name.length; i++)
        {
            int duplicate = 0;
            for (int j = i + 1; j < name.length; j++)
            {
                if (name[i].equals( name[j]))
                {
                    duplicate = duplicate + 1;
                   
                }
            }
         
            if (duplicate == 0)
            {
             total++;
                System.out.println(name[i] + " ");
            }
       
        }
            System.out.println("Number of Duplicates: " + total);
    }
}


No comments:

Post a Comment