将从.txt文件读取的字符串输入到数组中

时间:2017-05-02 01:38:20

标签: java arrays string multidimensional-array

我正在为我的高中软件项目制作一张类似flash的flashcard。我可以通过将文字写入文件来存储单词及其各自的翻译,但我想知道是否有可能将它们读入2d数组。

我可以用逗号或其他角色分隔它们吗?

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

谢谢堆!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

  • 阅读文件
  • 解析文件中的每一行以确定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

我想下一步是让用户给你一个单词并让你返回正确的翻译。我会留给你的。

答案 2 :(得分:0)

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

    // 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(< your separating character here>),然后将其连接到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();