我正在爲一個項目創建一個學校程序,在該程序中,我將文字和翻譯寫入文件(由字符分隔)。我讀過,我可以通過哈希映射將它們讀入數組中。我只是想知道,如果有人能指出我如何做到這一點正確的方向。通過散列圖從文本文件中檢索變量
如果有人更好地瞭解如何存儲和檢索我想學的單詞。我寫入文件的原因是用戶可以根據需要存儲儘可能多的單詞。
感謝你這麼多:d
我正在爲一個項目創建一個學校程序,在該程序中,我將文字和翻譯寫入文件(由字符分隔)。我讀過,我可以通過哈希映射將它們讀入數組中。我只是想知道,如果有人能指出我如何做到這一點正確的方向。通過散列圖從文本文件中檢索變量
如果有人更好地瞭解如何存儲和檢索我想學的單詞。我寫入文件的原因是用戶可以根據需要存儲儘可能多的單詞。
感謝你這麼多:d
您可以使用java.util.HashMap
來存儲用戶的單詞和相關的翻譯:
String userWord = null;
String translation = null, translation1 = null;
Map<String, String[]> map = new HashMap();
map.put(userWord, new String[] { translation, translation1 });
String[] translations = map.get(userWord);
這map
讓您單userWord
映射到多個翻譯。
下面是學習如何使用BufferedReader中的引用:BufferedReader
這裏有一個參考學習如何使用的FileReader:FileReader
import java.io.*;
class YourClass
{
public static void main() throws IOException
{
File f = new File("FilePath"); // Replace every '\' with '/' in the file path
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "";
String FileString = "";
while((line = br.readLine()) != null)
{
// Now 'line' contains each line of the file
// If you want, you can store the entire file in a String, like this:
FileString += line + "\n"; // '\n' to register each new line
}
System.out.println(FileString);
}
} // End of class
我還是個新手,也不要太瞭解HashMap
,但我可以告訴你如何將它保存在一個String數組:
FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
FileString.replaceAll("\\s+", " ")
- 替換1個或多個空格用1層的空間,所以以避免任何邏輯錯誤。
FileString.split(" ")
- 返回由空格分隔的每個String的String數組。
你可以嘗試這樣的事情
File f = new File("/Desktop/Codes/Text.txt");
// enter your file location
HashMap<String, String[]> hs = new HashMap<String, String[]>();
// throw exception in main method
Scanner sc = new Scanner(f);
String s="";
while(sc.hasNext()){
s = sc.next();
// create a method to search translation
String []trans = searchTrans(s);
hs.put(s, trans);
}
你說的「一個字符分隔」是什麼意思?你不需要特殊的角色。你可以通過一個空格分隔它們。 –
@ChousehouseCoder是啊......我只是想,也許他們會在卡片中使用空格,所以它會更容易使用一個非常模糊的字符 –
然後,您可以使用我的方法,但沒有'FileString.replaceAll(「\ \ s +「,」「)'行,你可以這樣做:'FileString = FileString.split(SpecialCharacter)' –