import java.util.ArrayList;
import java.util.Scanner;

/**
 * A simple class for formatting text messages.
 *
 * This class illustrates the use of the ArrayList class.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class TextFormatter
{

    /**
     * The entry point of the program
     *
     * @param args  The command-line arguments
     */
    public static void main(String[] args)
    {
       ArrayList message;
       int       displayWidth, i, width;
       Scanner   scanner;       
       String    word;


       // Initialization
       displayWidth = 20;
       scanner = new Scanner(System.in);       

       // Construct a new ArrayList
       message = new ArrayList();


       // Prompt the user to enter the message
       // one word at a time
       do 
       {
          System.out.printf("Next word: ");
          word = scanner.nextLine();
          message.add(message.size(), word);
       } 
       while (!word.equals(""));


       System.out.printf("\n\n\n");

       // Format the message so that it fits in
       // a fixed-width display
       width = displayWidth;
       for (i=0; i < message.size(); i++) 
       {
          // The generic Object must be cast as a String
          word = (String)(message.get(i));

          if (width+word.length()+1 > displayWidth) 
          {
             width = word.length();
             System.out.printf("\n");
             System.out.printf("%s", word);
          } 
          else 
          {
             width = width + word.length() + 1;
             System.out.printf(" %s", word);
          }
       }
    }

}
