简体   繁体   English

Java程序可对文本文件中的行,字符和单词进行计数

[英]Java program to count lines, char, and words from a text file

My output for the number of words and char keeps giving me zero. 我的单词和char数量输出始终为零。 If anyone could help me find the error in my code that would be great. 如果有人可以帮助我在代码中找到错误,那将是很好的。 The code enclosed by the stars is the code given by our teacher and we are required to put this in our program. 星星围住的代码是老师给的代码,我们需要将其放入程序中。

Thank you! 谢谢!

** Our teacher told us not to use the buffered method. **我们的老师告诉我们不要使用缓冲方法。 Also if I changes the lineNum method would it still override other methods? 另外,如果我更改lineNum方法,它将仍然覆盖其他方法吗? Part of the assignment is to use at least two methods in our program**** 部分工作是在我们的程序中至少使用两种方法****

** I edited my code based on everyones advice** It is now printing the correct numbers! **我根据大家的建议编辑了代码**现在可以打印正确的数字! How can I implement my two methods within this? 如何在其中实现我的两个方法? A suggestion was that I use the for loop for the wordCount method. 有人建议我将for循环用于wordCount方法。 I also need help with counting number of paragraphs A good starting point? 我还需要帮助计算段落数一个好的起点?

import java.util.*;
import java.io.*;

public class WordStats1 {

public static void main(String[] args) {
    try {

        Scanner input = new Scanner(new FileReader("data.txt"));
        //int totalLines = lineNum(input);
        //int wordCount = wordCount(input); 
        //int countChar = countChar(input);


        PrintWriter output = new PrintWriter(new FileOutputStream(
                "newfile.txt"));

        int lineNum = 0;
        int wordCount = 1;
        int charCount = 0; 

        while (input.hasNextLine()) {
            String line;
            line = input.nextLine();

            //output.println(lineNum + ": " + line);

            lineNum++;

            String str [] = line.split((" "));
              for ( int i = 0; i <str.length ; i ++) {
                if (str [i].length() > 0) {
                  wordCount ++; 
                }
              }
              charCount += (line.length());

        }

        System.out.println(lineNum);
        System.out.println(wordCount); 
        System.out.println(charCount); 
        input.close();
        output.close();

        System.out.print("File written.");

    }

    catch (FileNotFoundException e) {
        System.out.println("There was an error opening one of the files.");
    }

} } }}

The issue is that, once you've called lineNum() , you are at the end of the file. 问题是,一旦您调用lineNum() ,您就位于文件的末尾。 When wordCount() and countChar() call hasNextLine() , this returns false and the functions return zero. wordCount()countChar()调用hasNextLine() ,此方法返回false ,函数返回零。

For some ideas on how to rewind a Scanner , see Java Scanner "rewind" . 有关如何倒带Scanner一些想法,请参阅Java扫描器“倒带”

You need to do your linecount, word count and character count all inside a single loop. 您需要在一个循环内完成行数,字数和字符数的计算。 By having 3 functions, the very first function call to lineNum iterates over your scanner object, then the other two function calls return 0 because the scanner object has already read the file and as it is at the end of the file there is nothing left to read. 通过具有3个函数,对lineNum的第一个函数调用将在扫描程序对象上进行迭代,然后其他两个函数调用将返回0,因为扫描程序对象已经读取了文件,并且文件的末尾没有任何剩余内容。读。

I would suggest you edit your teachers code, in particular the while loop. 我建议您编辑您的老师代码,尤其是while循环。 Remove the 3 functions and the corresponding function calls and have the program do all of your counting inside the loop inside the main() function. 删除3个函数和相应的函数调用,并让程序在main()函数内的循环内进行所有计数。

int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (input.hasNextLine()) {
  // read a line from the input file
  String line = input.nextLine();

  // increment line count
  lineCount++;

  // split line into words and increment word count
  String str [] = line.split((" "));
  for ( int i = 0; i <str.length ; i ++) {
    if (str [i].length() > 0) {
      wordCount ++; 
    }
  }

  // increment char count
  charCount += (line.length());
}

EDIT 编辑

Given that you have said you need to use 2 methods, heres what I suggest: 鉴于您已经说过需要使用2种方法,以下是我的建议:

Move the word counting code above (the for loop) into a function of its own, it takes a String argument (the current line) and returns an integer. 将上面的单词计数代码(for循环)移至其自身的函数中,它接受String参数(当前行)并返回整数。 You can keep calling this from inside the loop. 您可以继续从循环内部调用它。

wordCount += countWordsInString(line);

The lineNum() method essentially 'consumes' the file, so input.hasNextLine() always returns false in the wordCount() and countChar() methods, hence you get zero in those two cases. lineNum()方法本质上是“消耗”文件,因此input.hasNextLine()在wordCount()和countChar()方法中始终返回false,因此在这两种情况下都为零。

Either combine all three methods in one uber-counter and process the file once, or load the file into some temporary variable such as a string and pass that into the three methods. 将这三种方法合并在一个超级计数器中,然后一次处理文件,或者将文件加载到某个临时变量(例如字符串)中,然后将其传递给这三种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM