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 == '
') ++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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…