I'm writing a program that for one part asks for the program to print how many characters (including whitespaces) are in a file. The code I have right now though returns 0 every time though and I'm not sure why it isn't counting the characters.
public int getcharCount(Scanner textFile) {
int count = 0;
while(textFile.hasNext()) {
String line = textFile.nextLine();
for(int i=0; i < line.length(); i++)
count++;
}
return count;
}
Edit: The specifications for my program say that I should use a scanner. I don't believe it is making it to the for loop though I'm not sure. When I used the same technique to count the number of lines in the file, it worked perfectly. That code was:
public int getLineCount(Scanner textFile) {
int lineCount = 0;
while(textFile.hasNext()) {
String line = textFile.nextLine();
lineCount++;
}
return lineCount;
}
And we aren't required to check if the line contains anything or not. If it appears in the middle of the text file, it should however be counted as one character.
I don't know why it does not work (and the code below will not fix it), but
for(int i=0; i < line.length(); i++)
count++;
can be written more concise as
count += line.length();