Formatting lines

This week the project is to read a file of ASCII text, and break the lines between words at a good spot.

I use a standard utility program called fmt, which does this job. Here are two runs of the utility program:

J:\fall07\csc1550\assign>fmt -72 input.txt Once upon a time there were three bears, a Mama, a Papa, and a Baby Bear, and they all lived together in a house in the woods. One morning Mama bear cooked oatmeal, and dished it out at the kithcen table. When they all sat down for breakfast, the oatmeal was too hot to eat, so they decided to go for a walk in the woods while it cooled down. While the bears were away, a little girl came walkiong up to the house. Her name was Goldilocks, and she walked right into the bear's kitchen without even knocking! J:\fall07\csc1550\assign>fmt -30 input.txt Once upon a time there were three bears, a Mama, a Papa, and a Baby Bear, and they all lived together in a house in the woods. One morning Mama bear cooked oatmeal, and dished it out at the kithcen table. When they all sat down for breakfast, the oatmeal was too hot to eat, so they decided to go for a walk in the woods while it cooled down. While the bears were away, a little girl came walkiong up to the house. Her name was Goldilocks, and she walked right into the bear's kitchen without even knocking! J:\fall07\csc1550\assign>
As you can see, the fmt program takes two arguments on the command line. One is a number, and the other is the name of a file. Then it types the file, breaking up lines at word boundaries so that the longest line is no longer than the number parameter.

I think the rules go like this:

So how do I read words from a file?

A Scanner has a next() method which seems perfect for the job. Here's an example, which reads words from a file.
import java.util.Scanner; import java.io.FileInputStream; public class Hu { public static void main(String [] args) throws java.io.FileNotFoundException { if (2 != args.length) { System.out.println("please put a number and filename on command line"); } FileInputStream herbert = new FileInputStream(args[1]); // I did type two args, no? Scanner scn = new Scanner(herbert); while (scn.hasNext()) { String w = scn.next(); System.out.println(w); } } }

You'll turn in:

  1. A debugging diary, describing in intricate, well-edited, gory detail all the various problems you had getting your program to run.
  2. A printout of the source file(s).
  3. A printout of your sample input.
  4. A printout of your program's output, showing it changing the sample input using two different output line lengths.