使用ArrayList查找并报告文件中最长字出现的所有行号

时间:2016-11-08 17:03:12

标签: java arraylist

该程序提供命令行参数,它们是文本文件的名称,并返回基本统计信息,如字符数,字数和行数,平均字长,以及每个字母和字长的数量。

除了这个以外我还能正常工作:使用ArrayList查找并报告文件中最长字出现的所有行号,以跟踪行号,因为我们不知道有多少次出现最长的单词。如果存在两个或更多相同最长长度的不同单词,则仅跟踪第一个单词。 我该怎么做?

  try {
    fileName = file.getName();
    Scanner fileScan = new Scanner(file);

    while (fileScan.hasNextLine()) { // Scan each line of the file
      lineNumber++;

      String line = fileScan.nextLine();

      // Count the number of occurrences of each alphabet(convert all to lower-case)
      for (int i = 0; i < line.length(); i++) {
        current = line.toLowerCase().charAt(i);

        if (current >= 'a' && current <= 'z') {
          letterCount[current - 'a'] ++; // 
        }

      }
      charCount += line.length();

      Scanner lineScan = new Scanner(line);
      lineScan.useDelimiter(DELIMITERS);
      while (lineScan.hasNext()) { // Scan each line into words using custom delimiters
        word = lineScan.next();
        wordCount++;

        // Find the no. of words of each length
        for (int i = 1; i <= MAX_WORD_LENGTH; i++) {
          if (word.length() == i) {
            wordLengthCount[i] ++;
          }
        }

      }


      lineScan.close();
    }

    // Find the average word length 
    for (int i = 1; i <= MAX_WORD_LENGTH; i++) {
      totalWordLength += (i * wordLengthCount[i]);
    }
    averageWordLength = (double) totalWordLength / wordCount;

    fileScan.close();
  } catch (FileNotFoundException e) {
    System.err.println("Invalid file path: " + file.getName());
  }

1 个答案:

答案 0 :(得分:0)

由于这是家庭作业,只需要一个部分解决方案来查看一些方法和可用的API使用方法:

这里线的方法是将最长的字保持在当前处理的线上。如果找到更长的单词,请清除列表。

    Path path = Paths.get("/home/...");

    int longestWordLength = 0;
    List<Integer> linesWithLongestWord = new ArrayList<>();

    int lineno = 0;
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    for (String line : lines) {
        ++lineno; // 1-based line numbers
        String[] words = line.split("\\P{L}+");
        int longest = Stream.of(words)
                .mapToInt(String::length)
                .max().orElse(0);
        if (longest > longestWordLength) {
            linesWithLongestWord.clear();
            longestWordLength = longest;             
            linesWithLongestWord.add(lineno);
        } else if (longest == longestWordLength) {
            linesWithLongestWord.add(lineno);
        }
    }        
    System.out.printf("Max %d, %s%n", longestWordLength, linesWithLongestWord);

使用String.split(regular_expression)派生单词,其中\P{L}为非字母(大写P =非)。

为了方便起见,我在单词上输入java 8流来获取最大长度。您可能希望循环外的局部变量中的最大单词。这里&#34;最长的单词&#34;减少到一个长度。

在循环之后,人们可以知道什么是最大的单词等等。