【问题标题】:Retrieving variables from a text file through a hashmap通过哈希图从文本文件中检索变量
【发布时间】:2017-06-06 05:10:14
【问题描述】:

我正在为一个项目创建一个学校计划,在该项目中我将文字和翻译文件(由一个字符分隔)。我读过我可以通过哈希映射将它们读入数组。我只是想知道是否有人可以为我指出正确的方向如何做到这一点。

如果有人对如何存储和检索我想学习的单词有更好的了解。我写入文件的原因是用户可以存储任意数量的单词。

非常感谢:D

【问题讨论】:

  • 你说的'被一个字符分隔'是什么意思?为此,您不需要特殊字符。您可以通过空格分隔它们。
  • @CoffeehouseCoder 是的......我只是想也许他们会在卡片中使用一个空格,所以使用一个非常不起眼的角色会更容易
  • 那么你可以使用我的方法,但是没有FileString.replaceAll("\\s+", " ")这一行,你可以这样做:FileString = FileString.split(SpecialCharacter)

标签: java arrays string multidimensional-array hashmap


【解决方案1】:

您可以使用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 映射到多个翻译。

【讨论】:

    【解决方案2】:

    这里是学习如何使用 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(" ") - 返回由空格分隔的每个字符串的字符串数组。

    【讨论】:

      【解决方案3】:

      你可以试试这样的

          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);
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        • 2020-11-10
        • 2013-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多