modifying a program to make second argument
hey guys, i have written a program which searches through a file in
order to ouput the number of characters, words and lines contained in a
certain file.. this works fine but i was hoping to take this one step
further.. in order to output the number of occurences of a word and
also the number of lines that word appears on..
for instance if i entered 'java WordCount bob.txt the' then the output
would include the number of occurences of the word 'the' and also the
number of lines which contain 'the'..
the code i have so far
is:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
import java.io.*;
public class WordCount {
private static void count(String name, BufferedReader in) throws
IOException {
long numLines = 0;
long numWords = 0;
long numChars = 0;
String line;
do {
line = in.readLine();
if (line != null)
{
numLines++;
numChars += line.length();
numWords += countWords(line);
}
}
while (line != null);
System.out.println(name + "\t" + numLines + "\t" +
numWords + "\t" + numChars);
}
/**
* Open file, count its words, lines and characters
* and print them to standard output.
* @param fileName name of file to be processed
*/
private static void count(String fileName) {
BufferedReader in = null;
try {
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
count(fileName, in);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
/**
* Count words, lines and characters of given input stream
* and print them to standard output.
* @param streamName name of input stream (to print it to stdout)
* @param input InputStream to read from
*/
private static void count(String streamName, InputStream input) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(inputStreamReader);
count(streamName, in);
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Determine the number of words in the argument line.
* @param line String to be examined, must be non-null
* @return number of words, 0 or higher
*/
private static long countWords(String line) {
long numWords = 0;
int index = 0;
boolean prevWhitespace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhitespace = Character.isWhitespace(c);
if (prevWhitespace && !currWhitespace) {
numWords++;
}
prevWhitespace = currWhitespace;
}
return numWords;
}
public static void main(String[] args) {
if (args.length == 0) {
count("stdin", System.in);
} else {
for (int i = 0; i < args.length; i++) {
count(args[i]);
}
}
}
}
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
any ideas how to modify this code in order to produce the new outputs?
Thank you all for your help
Sara