用于计算文本文件中的行、字符和单词的 Java 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23137966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:00:58  来源:igfitidea点击:

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

java

提问by user3546001

My output for the number of words and char keeps giving me zero. 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? Part of the assignment is to use at least two methods in our program****

** 我们的老师告诉我们不要使用缓冲方法。另外,如果我更改 lineNum 方法,它是否仍会覆盖其他方法?部分作业是在我们的程序中至少使用两种方法****

** 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. I also need help with counting number of paragraphsA good starting point?

** 我根据大家的建议编辑了我的代码** 现在正在打印正确的数字!如何在其中实现我的两种方法?一个建议是我对 wordCount 方法使用 for 循环。 我还需要帮助计算段落数一个好的起点?

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.");
    }

} }

} }

采纳答案by Husman

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. 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.

我建议你编辑你的教师代码,特别是 while 循环。删除 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. You can keep calling this from inside the loop.

将上面的单词计数代码(for 循环)移动到它自己的函数中,它接受一个 String 参数(当前行)并返回一个整数。您可以继续从循环内部调用它。

wordCount += countWordsInString(line);

回答by NPE

The issue is that, once you've called lineNum(), you are at the end of the file. When wordCount()and countChar()call hasNextLine(), this returns falseand the functions return zero.

问题是,一旦您调用了lineNum(),您就位于文件的末尾。当wordCount()countChar()call 时hasNextLine(), this 返回false并且函数返回零。

For some ideas on how to rewind a Scanner, see Java Scanner "rewind".

有关如何倒带 a 的一些想法Scanner,请参阅Java Scanner“倒带”

回答by stridecolossus

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.

要么将所有三种方法组合在一个超级计数器中并处理一次文件,要么将文件加载到某个临时变量(例如字符串)中并将其传递给三种方法。