Hashtable存取數據代碼實例

//輸入一個英語句子,把裏面每個單詞出現的次數統計出來

package ch22;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Exec22_10 extends JFrame {
    
public Exec22_10() {
        String out 
= "", output = "";
        Hashtable ht 
= new Hashtable();
        String str 
= JOptionPane.showInputDialog("輸入一個英語句子");
        StringTokenizer st 
= new StringTokenizer(str, " ,.?!");
        ht.clear();
        
// 存在hash表裏的數據,一定要Enumeration纔可以掉出來的
        while (st.hasMoreTokens()) {
            out 
= st.nextToken();// 無符號單詞
            for (int i = 0; i < out.length(); i++{
                output 
= String.valueOf(out.charAt(i));
                Object count 
= ht.get(output);
                
if (count == null{
                    count 
= (Integer) 1;
                    ht.put(output, count);
                }
 else {
                    
int temp = ((Integer) count).intValue();
                    ht.put(output, 
new Integer(temp + 1));
                }

            }


            System.out.println(
"單詞 出現次數 ");
            
// 這個是把村在hash表裏的東西取出來
            Enumeration items = ht.keys();// 返回此哈希表中的鍵的枚舉,就是把所有的額鍵給列舉出來
            while (items.hasMoreElements()) {
                String key 
= (String) (items.nextElement());
                Object val 
= ht.get(key);
                System.out.println(key 
+ " " + val + " ");
            }


        }

    }


    
public static void main(String[] args) {
        Exec22_10 fegor 
= new Exec22_10();
        fegor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fegor.setVisible(
true);
        fegor.setSize(
600460);
    }

}

/*
Object count;

ht.put(Object,Object)
可以這樣放

ht.put(Object,count)
加入我想把count+1後再放進去,不能直接加
定義個第三者
int temp;

先把count強制轉換成Integer,然後再取出Integer裏面的值
((Integer)count).intValue();
把取出來的值賦給temp
temp = ((Integer)count).intValue();
新建一個Integer對象,
Integer fegor = new Integer(temp+1);
然後放到裏面去。
ht.put(Object,fegor);

Object對象要想得到int值,就必須強制抓換取值。
也就是說,int數要想坐到Object的位置上,必須是Integer對象。

只要是這樣的就是強制轉換
(Integer)obj;
這樣說明是一個Integer對象,new的一個
Integer(temp)
*/

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章