Reputation: 11
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
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
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
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