馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
學習網站: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.read[color=rgb(68, 68, 68) !important]Line()) != 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);
}
}
}
}
}
|
評分
-
查看全部評分
|