user1998585
user1998585

Reputation: 11

Word Count of a file using String Arrays (JAVA)

        while (scan.hasNextLine()) {
        String thisline = scan.nextLine();
        totalnumber.countthelines++; //linecount works
             for(int i = 0; i < thisline.length();i++){
                  totalnumber.charactercounter++;  //chararacter count works
                  String [] thewords = thisline.split (" ");
                  totalnumber.wordcounter = thewords.length;  //does not work
             }
        }

I am having trouble getting my wordcounter to work(I am already able to count the characters and lines). I have tried many different ways to make it work, but it always ends up only counting the words from the last line of the read in file. Any suggestions on how to make it read every single line instead of just the last? Thanks

Upvotes: 0

Views: 1593

Answers (3)

cpp_ninja
cpp_ninja

Reputation: 347

for(int i = 0; i < thisline.length(); i++) {
    totalnumber.charactercounter++;  //chararacter count works
}

String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length;  //does not work

Upvotes: 0

Orab&#238;g
Orab&#238;g

Reputation: 11992

Well :

totalnumber.wordcounter += thewords.length

should be enough !

You just forgot to add the number of words... So the entiere code is :

while (scan.hasNextLine()) {
    String thisline = scan.nextLine();
    totalnumber.countthelines++; //linecount works
    totalnumber.charactercounter+=thisline.length();  //chararacter count works
    String [] thewords = thisline.split (" ");
    totalnumber.wordcounter += thewords.length; 
    }

(Sorry about the multiple edits. Sometime, it's so obvious... ;)

Upvotes: 2

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

You need:

String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;

outside of the loop iterating the characters. Note the += instead of =.

Upvotes: 1

Related Questions