/**
 * Generates random multiplication problems (intended for practice)
 * @author Hyrum D. Carroll
 * @version 0.2 (April 16, 2019)
 */
import java.util.Scanner;
import java.util.Random;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class MathPractice{

    final static int NUMBER_OF_PROBLEMS = 20;  // number of practice problems

    public static void main( String[] args ){
        // Overview:
        // Request an output filename from the user
        // Try to open the file
        // for the number of problems to generate
        //     randomly choose 2 numbers and write them to a file
        // close the file

        Scanner stdinScanner = new Scanner( System.in ); // user's input
        String filename; // user's filename
        int num1;  // temp variable for math problems
        int num2;  // temp variable for math problems

        // file objects
        FileWriter fw = null;
        BufferedWriter bw = null;
        PrintWriter pw = null;

        // random number generator object
        Random rand = new Random();

        boolean foundError = false;  // matches the error stated of the PrintWriter

        try{
            // Request an output filename from the user
            System.out.print("Please enter the output filename: ");
            filename = stdinScanner.next();

            // Try to open the file
            fw = new FileWriter( filename );
            bw = new BufferedWriter( fw );
            pw = new PrintWriter( bw );
            //pw = new PrintWriter( new BufferedWriter( new FileWriter( filename )));
        }catch( InputMismatchException e ){
            System.err.println("Sorry, there was an error parsing your input!" );
            return;
        }catch( FileNotFoundException e ){
            System.err.println("Sorry, that was not a valid filename: " + e.getMessage() );
            // Future: Repeatedly ask the user for a valid filename
            return;
        }catch(  Exception e ){
            System.err.println("ERROR: " + e.getMessage() );
            return;
        }

        // for the number of problems to generate
        for( int i = 0; i < NUMBER_OF_PROBLEMS && !foundError; i++){
            // randomly choose 2 numbers and write them to a file
            num1 = rand.nextInt( 10 );
            num2 = rand.nextInt( 10 );

            // write the problem to the file
            pw.println( num1 + " * " + num2 + " = ");
            if( pw.checkError() ){
                System.err.println("Write to file failed!" );
                foundError = true;
            }
        }

        pw.close();
    }
}