Source of ReadAllWords.java


  1: import java.util.Scanner;
  2: import java.util.ArrayList;
  3: import java.io.File;
  4: import java.io.FileNotFoundException;

  6: public class ReadAllWords {

  8:     public static void main(String[] args)
  9:             throws FileNotFoundException {
 10:         Scanner kbd = new Scanner(System.in);
 11:         ArrayList<String> words = new ArrayList<String>();
 12:         Scanner fin;
 13:         String name;
 14:         String word;

 16:         System.out.print("Enter the name of the file: ");
 17:         name = kbd.nextLine();
 18:         fin = new Scanner(new File(name));
 19:         while (fin.hasNext()) {
 20:             words.add(fin.next());
 21:         }
 22:         fin.close();

 24:         System.out.println("\n" + name + " has " + words.size()
 25:                 + " words in it.\n"
 26:                 + "The first is " + words.get(0)
 27:                 + " and the last is " + words.get(words.size() - 1) + "\n");
 28:         System.out.println("The middle word is "
 29:                 + words.get(words.size() / 2) + ".\n");
 30:     }

 32: }