import java.io.*;
import java.util.*;

/**
 * An application that asks the user simple addition questions.
 *
 * This application demonstrates the use of console I/O and file
 * output.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Quizzer
{
    private static final int NUMBER_OF_QUESTIONS = 10;    

    /**
     * The entry point of the application.
     *
     * @param args  The command-line arguments (which are ignored)
     */
    public static void main(String[] args)
    {
        boolean        status;        
        BufferedReader keyboard;
        int            actual, correct, expected, left, right;
        PrintWriter    log;        
        Random         rng;
        String         line;
        
        correct  = 0;        
        rng      = new Random();
        keyboard = new BufferedReader(new InputStreamReader(System.in));

        // Ask the questions and check the answers
        for (int i=0; i<NUMBER_OF_QUESTIONS; i++)
        {
            left  = rng.nextInt(10);
            right = rng.nextInt(10);
            expected = left + right;

            System.out.printf("%d. What is %d + %d? ", i+1, left, right);
            try
            {
                line = keyboard.readLine();
                try
                {
                    actual  = Integer.parseInt(line);
                    status = (actual == expected);                
                }
                catch (NumberFormatException nfe)
                {
                    status = false;
                }
            }
            catch (IOException ioe)
            {
                status = false;
            }
            
            if (status)
            {
                ++correct;
                System.out.printf("Correct!\n");
            }
            else
            {
                System.out.printf("Sorry, that's not correct.\n");
            }
        }

        // Create a log file that contains a summary of the results
        try
        {
            log = new PrintWriter(new File("results.txt"));
            log.printf("Correct:   %2d\n", correct);
            log.printf("Incorrect: %2d\n", NUMBER_OF_QUESTIONS - correct);
            log.close();
        }
        catch (FileNotFoundException fnfe)
        {
            System.out.printf("Unable to create the log file.");
        }
    }
    

}
