【问题标题】:Inputting string read from a .txt file into an array将从 .txt 文件中读取的字符串输入到数组中
【发布时间】:2017-05-02 01:38:19
【问题描述】:

我正在为我的高中软件项目制作一个类似抽认卡的应用程序。我可以通过将单词写入文件来存储单词及其各自的翻译,但我想知道是否有可能将它们读入二维数组。

我可以用逗号或其他字符分隔它们吗?

此外,还有一种方法可以将单词及其各自的翻译联系起来。例如,如果我调用了单词'x',如果它在数组中,是否有一个函数可以调用单词'translated x'?

谢谢大家!!

【问题讨论】:

    标签: java arrays string multidimensional-array


    【解决方案1】:

    您可能想查看地图。这样你就可以通过单词本身来查找每个单词,而不是遍历一个数组。地图使用键值对。不幸的是,它们是单向的(你不能通过它的值来查找一个键)。 https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

    【讨论】:

    • 嗨。感谢你的回答。我查看了地图,但找不到让用户输入自己的话的方法。有没有办法做到这一点?
    • 欢迎来到精彩的编程世界!询问用户输入不是地图的工作。地图只是程序其余部分用来存储东西并再次查找的工具。如果您希望您的用户能够添加单词,您必须编写要求用户输入单词、要求用户输入翻译、接受这些答案并将单词存储在您的地图中的代码。然后,您需要为用户提供一种方法,指定他想开始输入单词、开始测验,以及其他任何事情......别担心,这会很有趣!
    • 我明白,但我不明白如何将用户输入的单词与地图链接,以及当用户输入更多单词时如何创建新地图......
    【解决方案2】:

    让我们稍微分解一下这个问题。

    • 读取文件
    • 解析文件中的每一行以确定wordtranslation
    • wordtranslation 存储在数据结构中(@Glen Pierce 关于使用地图的建议很好)

    假设我们的文件是这样的,我们用逗号分隔单词和翻译(这也是我西班牙语词汇的范围):

    hello,hola
    good,bueno
    

    现在一些代码,让我们将文件读入地图。

    // a map of word to translation
    Map<String, String> wordMap = new HashMap<String, String>();
    
    // a class that can read a file (we wrap the file reader in a buffered reader because it's more efficient to read a file in chunks larger than a single character)
    BufferedReader fileReader = new BufferedReader(new FileReader("my-file.txt"));
    
    // a line from the file
    String line;
    
    // read lines until we read a line that is null (i.e. no more lines)
    while((line = fileReader.getLine()) != null) {
        // split the line, returns an array of parts
        String[] parts = line.split(",");
    
        // store the parts in meaningful variables
        String word = parts[0];
        String translation = parts[1];
    
        // now, store the word and the translation in the word map
        wordMap.put(word, translation);
    }
    
    // close the reader (note: you should do this with a try/finally block so that if you throw an exception, you still close the reader)
    fileReader.close();
    

    所以现在我们有了一个包含文件中所有单词和翻译的地图。给定一个单词,您可以像这样检索翻译:

    String word = "hello";
    String translation = wordMap.get(word);
    System.out.println(word + " translates to " + translation);
    

    输出:

    hello translates to hola
    

    我想下一步是让用户给你一个词,然后让你返回正确的翻译。我会把它留给你。

    【讨论】:

    • 非常感谢您的回答,这真的很有帮助。只是一个快速跟进的问题。您构建阅读部分的方式是一次只能存储一对单词,还是全部存储?这对我的项目没有任何应用,但我只是想知道。再次感谢!! :D
    • 当然,没问题。读取部分将一次读取整个文件一行,从每一行中提取word,translation 对,并将该对存储在wordMap 中。因此,它每次循环迭代只存储一对,但它会遍历文件中的每一行。这能回答你的问题吗?
    • 所以它一次存储一对,在while循环结束时,它会同时存储所有对吗?感谢您的耐心等待。我对此很陌生。
    • 没有同时发生的事情。这只是一个循序渐进的过程。循环说“我每次都会读一行,直到我读完”。如果文件中有 10 行,则循环将执行 10 次,每次它会读取一行并将其放入映射中。读完 10 行后,循环将结束,地图将包含 10 个单词,以及它们的匹配翻译。
    • 谢谢。这就解释得更清楚了!!
    【解决方案3】:

    您需要将单词存储在文本文件中(即它们是否需要持久化),还是可以将它们存储在内存中? 如果需要将它们写入文本文件,请尝试以下操作:

        // Create a file
        File file = new File("file.txt");
        // Initialize a print writer to print to the file
        PrintWriter pw = new PrintWriter(file);
        Scanner keyboard = new Scanner(System.in);
    
        // Populate
        boolean stop = false;
        do {
            String word;
            String translation;
            System.out.print("Enter a word: ");
            word = keyboard.nextLine().trim() + " ";
            if (!word.equals("quit ")) {
                pw.print(word);
                System.out.print("Enter its translation: ");
                translation = keyboard.nextLine().trim();
                pw.println(translation);
            } else {
                stop = true;
            }
        } while (!stop);
    
        // Close the print writer and write to the file
        pw.close();
    
        // Initialize a scanner to read the file
        Scanner fileReader = new Scanner(file);
    
        // Initialize a hash table to store the values from the file
        Hashtable<String, String> words = new Hashtable<String, String>();
    
        // Add the information from the file to the hash table
        while (fileReader.hasNextLine()) {
            String line = fileReader.nextLine();
            String[] array = line.split(" ");
            words.put(array[0], array[1]);
        }
    
        // Print the results
        System.out.println("Results: ");
        words.forEach((k, v) -> System.out.println(k + " " + v));
    
        fileReader.close();
        keyboard.close();
    

    请注意,我使用空格将单词与其翻译分开。您可以轻松地使用逗号或分号或您拥有的任何东西。只需将line.split(" ") 替换为line.split(&lt; your separating character here&gt;) 并将其连接到word = keyboard.nextLine().trim() 的末尾即可。

    如果你不需要保存信息,只需要收集用户的输入,那就更简单了:

    Scanner keyboard = new Scanner(System.in);
    
        // Initialize a hash table to store the values from the user
        Hashtable<String, String> words = new Hashtable<String, String>();
    
        // Get the input from the user
        boolean stop = false;
        do {
            String word;
            String translation;
            System.out.print("Enter a word: ");
            word = keyboard.nextLine().trim();
            if (!word.equals("quit")) {
                System.out.print("Enter its translation: ");
                translation = keyboard.nextLine().trim();
                words.put(word, translation);
            } else {
                stop = true;
            }
        } while (!stop);
    
        // Print the results
        System.out.println("Results: ");
        words.forEach((k, v) -> System.out.println(k + " " + v));
    
        keyboard.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多