註冊 登錄
Android 台灣中文網 返回首頁

jianrupan的個人空間 https://apk.tw/?1180935 [收藏] [複製] [分享] [RSS]

日誌

JAVA 學習:HashMap 應用學習

已有 326 次閱讀2021-12-2 17:11 |個人分類:軟體應用| 學習, HashMap, 應用

學習網站:https://www.youtube.com/watch?v=wOPDB2R41L0

public class Dictionary {
    public static void main(String[] args) throws Exception {
        // HashMap is dynamic data structure for collection of key-value mapping
        // HashMap 是可以直接由 key 對應 value 的動態資料結構
        /*
            What we want to do this:
                1.Load dictionary data from file
                2.Put data to HashMap
                3.Provide dictionary checking feature
            我們要做的事情是:
                1.從檔案讀取字典資料
                2.把資料放進 HashMap 中
                3.提供字典查詢的功能
        */
        // 建立 HashMao 物件 Create HashMap Object
        // HaspMap<KeyDataType, ValueDataType>
        HashMap<String, String> dic = new HashMap<String, String>();
        // 從檔案讀取資料 Load data from file
        // 避免中文亂碼
        String sFile = "H:/學習_JAVA/HashMap/Dictionary/src/Data.txt";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(sFile), "UTF-8");
        try (BufferedReader reader = new BufferedReader(isr)) {
            // FileReader in = new FileReader("H:/學習_JAVA/HashMap/Dictionary/src/Data.txt");
            // BufferedReader reader = new BufferedReader(in);
            String line;
            String english, chinese;
            int cutIndex;
            while((line = reader.readLine()) != null) {
                // 試印資料
                // System.out.println(line);
                cutIndex = line.indexOf(",");
                english = line.substring(0, cutIndex);
                chinese = line.substring(cutIndex+1, line.length());
                // 試印資料
                // System.out.println(english+"-"+chinese);
                // 把資料放進 HashMap 中 Put data into HashMap
                dic.put(english, chinese);  // 英文查中文
                dic.put(chinese, english);  // 中文查英文
            }
        }
        // 提供字典查詢的功能, 輸入 0 結束程式
        // Provide dictionary checking feature, enter 0 to exit program
        while(true) {
            System.out.println("輸入想查詢的文字 Enter keyword to check");
            String keyword = System.console().readLine();
            if(keyword.equals("0")) {
                break;
            } else {
                // if key exist, return value, else return null
                // 如果 key 存在, 回傳相對應的 value, 否則回傳 null
                String result = dic.get(keyword);
                if(result == null) {
                    System.out.println("查不到資料 No Data");
                } else {
                    System.out.println("查詢成功 Success: "+ result);
                }
            }
        }
    }
}

路過

雞蛋

鮮花

握手

雷人

評論 (0 個評論)

facelist

您需要登錄後才可以評論 登錄 | 註冊