This should count number of lines, words and characters into file.
But it doesn't work. From output it shows only 0
.
Code:
public static void main(String[] args) throws IOException {
int ch;
boolean prev = true;
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
// count the characters of the file till the end
while(in.hasNext()) {
ch = in.next().charAt(0);
if (ch != ' ') ++charsCount;
if (!prev && ch == ' ') ++wordsCount;
// don't count if previous char is space
if (ch == ' ')
prev = true;
else
prev = false;
if (ch == '\n') ++linesCount;
}
//display the count of characters, words, and lines
charsCount -= linesCount * 2;
wordsCount += linesCount;
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
I can't understand what's going on. Any suggestions?
Maybe my code will help you...everything work correct
You have a couple of issues in here.
First is the test for the end of line is going to cause problems since it usually isn't a single character denoting end of line. Read http://en.wikipedia.org/wiki/End-of-line for more detail on this issue.
The whitespace character between words can be more than just the ASCII 32 (space) value. Consider tabs as one case. You want to check for Character.isWhitespace() more than likely.
You could also solve the end of line issues with two scanners found in How to check the end of line using Scanner?
Here is a quick hack on the code you provided along with input and output.
Here is the test file input:
Here is the output:
The difference between character count is due to not counting whitespace characters which appears to be what you were trying to do in the original code.
I hope that helps out.
Different approach. Using strings to find line,word and character counts:
Note:
For other encoding styles use
new Scanner(new File(selectedFile), "###");
in place ofnew Scanner(selectedFile);
.###
is the Character set to needed. Refer this and wikiUse
Scanner
methods:Your code is looking at only the first characters of default tokens (words) in the file.
When you do this
ch = in.next().charAt(0)
, it gets you the first character of a token (word), and the scanner moves forward to the next token (skipping rest of that token).