Pages

get our extension

Search program

Wednesday 17 July 2013

Read a file and count the no of occurance of specific word

Example Input file
input.txt

class Employee
{
     private String name;
     public Integer age;
     protected Date dob;
     public Address addr;
     private Date doj;
     public  String designation;

}


SpecificWordCount.java


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

public class SpecificWordCount
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        String ch=null;
         int count=0;
         try
        {
           HashMap<String, Integer> hmap = new HashMap<String, Integer>();
           hmap.put("public", count);
           hmap.put("private", count);
           hmap.put("protected", count);
              while((ch=br.readLine())!=null)
              {
                  String[] word=ch.split(" ");
                  for(int i=0;i<word.length;i++)
                  {
                      if (word[i].equalsIgnoreCase("public"))
                      {
                         
                          int value=hmap.get("public");
                               value++;
                               hmap.put("public", value);
                         
                      }
                     
                      if (word[i].equalsIgnoreCase("private"))
                      {
                          int value=hmap.get("private");
                               value++;
                               hmap.put("private", value);
                         
                      }
                      if (word[i].equalsIgnoreCase("protected"))
                      {
                          int value=hmap.get("protected");
                               value++;
                               hmap.put("protected", value);         
                      }
                  }   
              }
              Set<String> keySet=hmap.keySet();
              for(String key : keySet)
              {
                  int value=hmap.get(key);
                  System.out.println(key + "-->" + value);
              }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }


output:

protected-->1
public-->3
private-->2

No comments:

Post a Comment