// File: ScannerExample.java
// Author: Nicholas Duchon
// Date: Sep 19, 2006

// Demonstrates the basic file I/O operations
// Uses the Scanner class for input
// Just throws I/O exceptions
// File not found would be a useful exception to catch and handle
// FileWriter --> BufferedWriter --> PrintWriter lets the code use
//    print, println and printf
// File --> Scanner opens a file using the text name of the file.

// This code also demonstrates handling the arguments to main.
// In jGrasp, Build --> Run Arguments shows the input arguments interface line

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ScannerExample {

   public static void main (String [] args) throws IOException {
      int flag = 0;
      if (args.length > 0) flag = Integer.parseInt (args[0]);
      
      Scanner stdin = new Scanner (System.in);

      // output
      if (flag == 0) {
         System.out.print ("File name for writing: ");
         String outputFileName = stdin.next();
         System.out.println ("Opening for writing: " + outputFileName);
         FileWriter     fw = new FileWriter     (outputFileName);
         BufferedWriter bw = new BufferedWriter (fw);
         PrintWriter    pw = new PrintWriter    (bw);
         for (int i = 0; i < 33; i++)
            pw.println ("" + i + " " + i*i);
         pw.close();
      } // end if output flag

      // input
      if (flag == 1) {
         System.out.print ("File name for reading: ");
         String inputFileName = stdin.next();
         System.out.println ("Opening for reading: " + inputFileName);
         Scanner in = new Scanner (new File (inputFileName));
         int value;
         int count = 0;
         while (in.hasNextInt()) {
            value = in.nextInt();
            System.out.println ("{" + count++ + "] - " + value);
         } // end while input file has more entries
         in.close();
      } // end if input flag

   } // end method main
   
} // end class ScannerExample