Wednesday, August 8, 2012

HashTable In Java

Here is a Hash Table program in java.

In this program we are going to,

 1]Accept n  records of student(Name,percentage)
 2]Disply details of all students
 3]Find out highest marks

 import java.util.*;
 import java.io.*;
 class Slip1_2
 {
   public static void main(String args[]) throws IOException
   {
     
       Slip1_2 htc = new Slip1_2();
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int opt=1;
      while(opt!=4)
       {
         
           System.out.println("1:Enter Record");
           System.out.println("2:Disply Details");
           System.out.println("3:Find Highest Marks");
           System.out.println("4:Exit");
           System.out.print("Select Option : ");
      
        int r=Integer.parseInt(br.readLine());
      
        System.out.println();
        
           switch(r)
           {
               case 1:htc.get_record();      break;
               case 2:htc.disp_record();    break;
               case 3:htc.highest_record(); break;
               case 4:System.exit(0);
           }//switch
       }//while
     }//main


     Hashtable ht =new Hashtable();
     //Enumeration names;
     String nm;
    Slip1_2(){ }
    void get_record() throws IOException
     {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter n Records of stud : ");       int n=Integer.parseInt(br.readLine());
       Double d;
          System.out.println();
          for(int i=0;i<n;i++)
          {
               System.out.print("Enter Name : ");    nm = br.readLine();
              System.out.print("Enter Percentage : ");   d = Double.parseDouble(br.readLine());
              System.out.println();
              ht.put(nm,d);
          }
      }
    
         
   
   
     void disp_record()
     {
         Enumeration names= ht.keys();
         //Returns an enumeration of the keys in this hashtable. <-=keys()
         while(names.hasMoreElements())     //Tests if this enumeration contains more elements.
         {
             nm=(String)names.nextElement();
                             //the next element of this enumeration.
 
              System.out.print(nm+" => "+ht.get(nm));
              //Returns the value to which the specified key is mapped in this hashtable.
              System.out.println();
         }
             System.out.println();
      }
  
     void highest_record()
     {
         Collection c=ht.values();
         //Object obj=Collections.max(c);
         //System.out.println("Highest Marks: "+obj);
         System.out.println("Highest Marks: "+Collections.max(c));
     }   
   
 }

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...