import java.io.*; import java.util.Scanner; public class FormatText1 { public static void main(String[] args) throws IOException { String[] a = new String[100]; // Create String array of 100 elem's int numWords; // Count # words in input File myFile = new File("inp2"); // Open file "inp2" Scanner in = new Scanner(myFile); // Make Scanner obj with opened file numWords = 0; while ( in.hasNext() ) { a[numWords] = in.next(); // Read next string (word) numWords++; // Count # words AND use next // array element for next word } String line; // 1 line line = ""; for ( int i = 0; i < numWords; i++ ) { if ( line.length() + 1 /* space */ + a[i].length() <= 30 ) { line = line + " " + a[i]; } else { System.out.println(line); // Next word can't fit line = a[i]; } } } }