dzungchaos

Java: VD về Hastable

Jul 2nd, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.50 KB | None | 0 0
  1. 1. Tim trong tu dien
  2. import java.util.*;
  3.  
  4. public class HashTableExample {
  5.     public static void main(String args[]) {
  6.         Hashtable tdav = new Hashtable();
  7.         tdav.put("Hello","Chao");
  8.         tdav.put("Begin","Bat dau");
  9.         tdav.put("End","Ket thuc");
  10.  
  11.         //Tim tu trong tu dien
  12.         String tu = "Begin";
  13.         if (tdav.containsKey(tu))
  14.             System.out.println(tu+" : "+tdav.get(tu));
  15.         else
  16.             System.out.println("Khong co tu:"+tu);
  17.     }
  18. }
  19.  
  20. 2. Dem so tu trung nhau
  21. import java.util.Enumeration;
  22. import java.util.Hashtable;
  23. import java.util.StringTokenizer;
  24.  
  25. public class countWords {
  26.     public static void main(String[] args) {
  27.         Hashtable h = new Hashtable();
  28.         String s = "to be or not to be";
  29.         StringTokenizer st = new StringTokenizer(s," ");
  30.         //System.out.println("So tu:"+st.countTokens());
  31.  
  32.         while (st.hasMoreTokens()) {
  33.             //System.out.println(st.nextToken());
  34.             String ns = st.nextToken();
  35.             if(h.containsKey(ns))
  36.             {
  37.                 int i = (int)h.get(ns);
  38.                 h.put(ns, ++i);
  39.                 //System.out.println(ns + " " + i);
  40.             }
  41.             else{
  42.                 h.put(ns, 1);
  43.                 //System.out.println(ns + " =1");
  44.             }
  45.         }
  46.  
  47.         Enumeration e2 = h.elements();
  48.         Enumeration e1 = h.keys();
  49.  
  50.         while (e1.hasMoreElements())
  51.             System.out.println(e1.nextElement().toString() + " " + e2.nextElement().toString());
  52.     }
  53. }
Add Comment
Please, Sign In to add comment