简体   繁体   中英

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

** 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 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. When wordCount() and countChar() call hasNextLine() , this returns false and the functions return zero.

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

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.

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.

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:

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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