【问题标题】:Make an array of words in alphabetical order in java, after reading them from a file从文件中读取它们后,在java中按字母顺序制作一个单词数组
【发布时间】:2016-03-13 17:11:53
【问题描述】:

我有以下代码可以打开和读取文件并将其分隔为单词。 我的问题是按字母顺序排列这些单词。

import java.io.*;

class MyMain {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Kennedy.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        int line_count=0;
        int byte_count;
        int total_byte_count=0;
        int fromIndex;
        while( (line = br.readLine())!= null ){
            line_count++;
            fromIndex=0;
            String [] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*");
            String line_rest=line;
            for (int i=1; i <= tokens.length; i++) {
                byte_count = line_rest.indexOf(tokens[i-1]);
                //if ( tokens[i-1].length() != 0)
                //System.out.println("\n(line:" + line_count + ", word:" + i + ", start_byte:" + (total_byte_count + fromIndex) + "' word_length:" + tokens[i-1].length() + ") = " + tokens[i-1]);
                fromIndex = fromIndex + byte_count + 1 + tokens[i-1].length();
                if (fromIndex < line.length())
                    line_rest = line.substring(fromIndex);
            }
            total_byte_count += fromIndex;
        }
    }
}

【问题讨论】:

  • 您的文件看起来如何?
  • 你应该考虑使用List,然后你可以直接调用Collections.sort(list)
  • @dinomario10 你的意思是不是数组令牌?
  • @NikolasCharalambidis 这是一个带有字母和符号的文本。
  • 使用TreeSet&lt;String&gt;

标签: java arrays file


【解决方案1】:

我会用Scanner1 读取File(我更希望File(String,String) 构造函数提供父文件夹)。而且,您应该记住在finally 块中明确地close 您的资源您可以使用try-with-resources statement。最后,对于 排序,您可以将 单词 存储在 TreeSet 中,其中 元素使用它们的 natural ordering2 进行排序。类似的,

File file = new File("C:/", "Kennedy.txt");
try (Scanner scanner = new Scanner(file)) {
    Set<String> words = new TreeSet<>();
    int line_count = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        line_count++;
        String[] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*");
        Stream.of(tokens).forEach(word -> words.add(word));
    }
    System.out.printf("The file contains %d lines, and in alphabetical order [%s]%n",
            line_count, words);
} catch (Exception e) {
    e.printStackTrace();
}

1主要是因为它需要较少的代码。
2或者在创建时提供Comparator

【讨论】:

  • @KaterinaTsellou 以上使用的是 Java 8+ lambdas。如果您使用的是 Java 的早期 (EOL) 版本,则可以使用 for-each 循环。否则,请解释您遇到的错误。
  • 匿名类不能继承最终类 Scanner
  • 此代码不是 Scanner 的子类。您使用的是什么版本的 Java?您的 IDE 合规级别设置为哪个版本?
  • 我用的是eclipse平台
  • Window > Preferences > Java > Compiler: "Compiler Compliance Level"
【解决方案2】:

如果您将标记存储在字符串数组中,请使用 Arrays.sort() 并获取自然排序的数组。在这种情况下,作为它的字符串,您将获得一个排序的令牌数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2018-06-11
    • 2023-03-21
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多