Mark Gold
Mark Gold

Reputation: 49

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

I am practicing to write a program that gets a text file from user and provides data such as characters, words, and lines in the text.

I have searched and looked over the same topic but cannot find a way to make my code run.

public class Document{
private Scanner sc;

// Sets users input to a file name
public Document(String documentName) throws FileNotFoundException {
    File inputFile = new File(documentName);
    try {
        sc = new Scanner(inputFile);

    } catch (IOException exception) {
        System.out.println("File does not exists");
    }
}


public int getChar() {
    int Char= 0;

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Char += line.length() + 1;

    }
    return Char;
}

// Gets the number of words in a text
public int getWords() {
    int Words = 0;

    while (sc.hasNext()) {
        String line = sc.next();
        Words += new StringTokenizer(line, " ,").countTokens();

    }

    return Words;
}

public int getLines() {
    int Lines= 0;

    while (sc.hasNextLine()) {
        Lines++;
    }

    return Lines;
}
  }

Main method:

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        DocStats doc = new DocStats("someText.txt");

        // outputs 1451, should be 1450
        System.out.println("Number of characters: "
            + doc.getChar()); 

        // outputs 0, should be 257
        System.out.println("Number of words: " + doc.getWords());
        // outputs 0, should be 49
        System.out.println("Number of lines: " + doc.getLines()); 

    }

}

I know exactly why I get 1451 instead of 1451. The reason is because I do not have '\n' at the end of the last sentence but my method adds numChars += line.length() + 1;

However, I cannot find a solution to why I get 0 for words and lines. *My texts includes elements as: ? , - '

After all, could anyone help me to make this work?

**So far, I the problem that concerns me is how I can get a number of characters, if the last sentence does not have '\n' element. Is there a chance I could fix that with an if statement?

-Thank you!

Upvotes: 3

Views: 1128

Answers (2)

tgkprog
tgkprog

Reputation: 4598

I would use one sweep to calculate all 3, with different counters. just a loop over each char, check if its a new word etc, increase counts , use Charater.isWhiteSpace *

import java.io.*;
/**Cound lines, characters and words Assumes all non white space are words so even () is a word*/
public class ChrCounts{

    String data;
    int chrCnt;
    int lineCnt;
    int wordCnt;
    public static void main(String args[]){
        ChrCounts c = new ChrCounts();
        try{
            InputStream data = null;
            if(args == null || args.length < 1){
                data = new ByteArrayInputStream("quick brown foxes\n\r new toy\'s a fun game.\nblah blah.la la ga-ma".getBytes("utf-8"));
            }else{
                data = new BufferedInputStream( new FileInputStream(args[0]));
            }
            c.process(data);
            c.print();
        }catch(Exception e){
            System.out.println("ee " + e);
            e.printStackTrace();
        }
    }

    public void print(){
        System.out.println("line cnt " + lineCnt + "\nword cnt " + wordCnt + "\n chrs " + chrCnt);
    }

    public void process(InputStream data) throws Exception{
        int chrCnt = 0;
        int lineCnt = 0;
        int wordCnt = 0;
        boolean inWord = false;
        boolean inNewline = false;
        //char prev = ' ';
        while(data.available() > 0){
            int j = data.read();
            if(j < 0)break;
            chrCnt++;
            final char c = (char)j;
            //prev = c;
            if(c == '\n' || c == '\r'){
                chrCnt--;//some editors do not count line seperators as new lines
                inWord = false;
                if(!inNewline){
                    inNewline = true;
                    lineCnt++;
                }else{
                    //chrCnt--;//some editors dont count adjaccent line seps as characters
                }
            }else{
                inNewline = false;
                if(Character.isWhitespace(c)){
                    inWord = false;
                }else{
                    if(!inWord){
                        inWord = true;
                        wordCnt++;
                    }
                }
            }
        }
        //we had some data and last char was not in new line, count last line
        if(chrCnt > 0 && !inNewline){
            lineCnt++;
        }
        this.chrCnt = chrCnt;
        this.lineCnt = lineCnt;
        this.wordCnt = wordCnt;
    }
}

Upvotes: 1

ParkerHalo
ParkerHalo

Reputation: 4430

After doc.getChar() you have reached the end of file. So there's nothing more to read in this file!

You should reset your scanner in your getChar/Words/Lines methods, such as:

public int getChar() {
    sc = new Scanner(inputFile);
...
    // solving your problem with the last '\n'
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        if (sc.hasNextLine())
            Char += line.length() + 1;
        else
            Char += line.length();
    }
    return char;
}

Please note that a line ending is not always \n! It might also be \r\n (especially under windows)!

public int getWords() {
    sc = new Scanner(inputFile);
...


public int getLines() {
    sc = new Scanner(inputFile);
...

Upvotes: 2

Related Questions