/*
 * MovieDatabase2.java
 *
 * A simple file-processing program that computes the average
 * runtime of movies with a particular rating (PG, R, etc.).
 *
 * Date: July 7, 2015
 */

import java.util.*;
import java.io.*;

public class MovieDatabase2 {
    // The name of the file containing the movie information.
    // We assume that it is in the same folder as this program.
    public static final String DATA_FILE_NAME = "movies.txt";

    public static void main(String[] args) throws FileNotFoundException {
        Scanner console = new Scanner(System.in);

        System.out.print("Enter a movie rating: ");
        String rating = console.next();
        findAverageRuntime(rating);
    }

    /*
     * findAverageRuntime - determines the average runtime of
     * all movies in the database with the rating specified by
     * targetRating.
     */
    public static void findAverageRuntime(String targetRating)
        throws FileNotFoundException
    {
        Scanner input = new Scanner(new File(DATA_FILE_NAME));

        int total = 0;     // sum of runtimes of movies with targetRating
        int count = 0;     // number of movies with targetRating

        while (input.hasNextLine()) {
            String record = input.nextLine();

            /*
             * Bug #1: we should split on tab characters, not newlines.
             * If we split on newlines, the entire record would be counted
             * as the first field in the record.
             */
            //String[] fields = record.split("\n");
            String[] fields = record.split("\t");

            String name = fields[0];
            String rating = fields[1];
            int runtime = Integer.parseInt(fields[2]);

            /*
             * Bug #2: using == to compare reference types will compare the
             * reference, not the objects themselves. Since these objects are
             * both strings, we want to know if they have the same characters,
             * not if the reference is the same.
             */

            //if (rating == targetRating) {
            if (rating.equals(targetRating)) {
                total += runtime;
                count++;
            }
        }

        if (count == 0) {
            System.out.println("There are no movies with that rating.");
        } else {
            double avg = (double)total / count;
            System.out.print("The average runtime of movies with that rating is ");
            System.out.printf("%.1f minutes.\n", avg);
        }
    }
}
