Thursday, 30 August 2012

some java example using hashmap



//some java example using hashmap
//DUPLICATE  CHARACTERNIN JAVA
package com.swain.cell;

import java.util.HashMap;

public class DuplicateCharacter {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

        String str = "Character duplicate word example java";
        char selectedchar='C';
        char ch1[]=str.toUpperCase().toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0; i<ch1.length; i++)
        {
            char ch=ch1[i];
            hm.put(ch,(hm.get(ch)==null?1:hm.get(ch)+1));
        }
     
        System.out.println(selectedchar+" contents  " + hm.get(selectedchar)+ " times.");
     
     
 
}

}
//DUPLICATE STRING IN JAVA
package com.swain.cell;

import java.util.HashMap;
import java.util.StringTokenizer;

public class DuplicateString {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

        String str = "java java android android java example";
        String selectedword="java";
         
        StringTokenizer t = new StringTokenizer(str);
        HashMap<String,Integer> hms=new HashMap<String,Integer>();
        
while(t.hasMoreTokens())
{
String word = t.nextToken();
hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));
}
System.out.println(selectedword+" contents  " + hms.get(selectedword)+ " times.");
        
    
}

}
//FACTORIAL IN JAVA
package com.swain.cell;

public class Factorial {
public static void main(String args[])
  {
     int n, c, fact = 1;
 
     n=5;
     if ( n < 0 )
        System.out.println("Number should be non-negative.");
     else
     {
        for ( c = 1 ; c <= n ; c++ )
           fact = fact*c;
 
        System.out.println("Factorial of "+n+" is = "+fact);
     }
  }

}
//FIBONACI SERIES IN JAVA
package com.swain.cell;

public class Fibonacci {

public static long fibonacci(int n) {
       if (n <= 1) return n;
       else return fibonacci(n-1) + fibonacci(n-2);
   }

   public static void main(String[] args) {
       int n=15;
       for (int i = 1; i <= n; i++)
           System.out.println(i + ":- " + fibonacci(i));
   }

}

No comments:

Post a Comment