/*
The WC () method operates on any input stream and calculates the number of characters, number of lines, and number of words. It tracks the parity and space of words in lastnotwhite. If no parameter is specified, wordcount uses system. In as the source code to generate an inputstreamreader object. The stream is then passed to the actual counting WC () method. When one or more parameters are executed, wordcount assumes that these file names exist and creates a filereader for each file. The filereader object storing the results is passed to the WC () method. In both cases, the results are printed before exiting.
*/
// A word counting utility.
Import java. Io .*;
Class wordcount {
Public static int intwords = 0;
Public static int intlines = 0;
Public static int intchars = 0;
Public static void WC (inputstreamreader ISR) throws ioexception {
Int C = 0;
Boolean lastwhite = true;
String whitespace = "/T/N/R ";
While (C = ISR. Read ())! =-1 ){
// Count characters.
Intchars ++;
// Count lines.
If (C = '/N '){
Intlines ++;
}
// Count words by detecting the start of a word
Int intindex = whitespace. indexof (C );
If (intindex =-1 ){
If (lastwhite = true ){
++ Intwords;
}
Lastwhite = false;
} Else {
Lastwhite = true;
}
}
If (intchars! = 0 ){
++ Intlines;
}
}
Public static void main (string [] ARGs)
{
Filereader fr;
Try {
If (ARGs. Length = 0 ){
// We're working with stdin
WC (New inputstreamreader (system. In ));
} Else {
// We're working with a list of files.
For (INT I = 0; I <args. length; I ++ ){
Fr = new filereader (ARGs [I]);
WC (FR );
}
}
} Catch (ioexception e ){
Return;
}
System. Out. println (intlines + "" + intwords + "" + intchars );
}
}