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();
Why are you using a Scanner ? A simple Reader would suffice. If you insist in using a Scanner, you must understand that it divides its input in fields separated by some pattern (a space by default), perhaps one can set an empty pattern so that the fields correspond with the characters (but again, that would be overkill, just use a Reader)
Have you already read everything from the Scanner before passing it to getcharCount()
?
You need to assign the file, open it, and reset to the beginning. You don't show any of that.
What delimiter are you setting for the scanner? You don't show it in your code, but you need to make it treat a line as a single token.
scanner.useDelimiter("\n");
Also, you say that the second code example worked perfectly. Did you print out the value of line to verify that it contained anything? It might have counted the lines properly, but if line didn't actually contain anything then that would help explain why it doesn't enter your for loop.
I haven't worked with Scanner too much, but wouldn't
textFile.hasNextline();
make a little more sense than
textFile.hasNext();
Just a thought--I'm not sure if that would have any major effect on the execution
精彩评论