ShortWords.java
import java.awt.*;
import java.io.*;
import java.awt.event.*;
// A program to count the number of short words in a
// typed in, write the result in a file
public class ShortWords {
public static void main(String[] args) {
BufferedReader reader;
PrintWriter result;
String curWord; // the current word
int count = 0; // count of short words seen
try {
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter a file name:");
String outfile = reader.readLine();
System.out.println("Enter words, one per line. Four-letter words will");
System.out.println("be written to file " + outfile);
System.out.println("End the program by entering a ctrl-d");
// create the output stream to write the answer
result = new PrintWriter(new FileWriter(new File(outfile)));
// get the first line of the file
curWord = reader.readLine();
while ( curWord != null ) {
if ( curWord.length() == 4 ) {
count++;
result.println(curWord);
}
// get the next line from the file
curWord = reader.readLine();
}
result.close();
System.out.println("Done. Total = " + count );
} catch ( IOException e) {
System.out.println(e);
}
}
}