This discussion is archived
2 Replies Latest reply: Nov 5, 2007 9:12 AM by 807603 RSS

Java programming count words, lines, characters and paragraphs

807603 Newbie
Currently Being Moderated
I have made it so my program counts lines and words but I dont know how to my it count characters and paragraphs (assuming a blank line is inserted to distinguish between paragraphs)... please help.

import java.io.*; // import classes for file I/O
import java.util.Scanner;

public class WordCountextra {

public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: WordCount <filename>");
return;
}
String currWord;
String currLine;
String currCharacter;
String inputFileName = args[0];
Scanner fileIn = null; // for file input
try {
// important: use these to read from and write to files
fileIn = new Scanner(new File(inputFileName));

// read each line, prepend current line number, and write out
int count = 0;
int countline = 0;
int countcharacter = 0;
int char = 0;
while (fileIn.hasNext()) {
currWord = fileIn.next();
count++;
}
fileIn = new Scanner(new File(inputFileName));
while (fileIn.hasNextLine()) {
currLine = fileIn.nextLine();
countline++;
}
System.out.println("Number of words in "+ inputFileName + ": " + count); // print numbered line to screen
System.out.println("Number of lines in "+ inputFileName + ": " + countline);
catch (IOException e) {
System.out.println("Error: can't find file " + inputFileName);
}
finally {
// close files
if (fileIn != null) {
fileIn.close();
}
}
}
}