/*
 * StudentDatabase.java
 *
 * A simple program that queries a text file database for student records.
 *
 * Author: S-111 Course Staff
 */

import java.util.*;     // needed for the Scanner class
import java.io.*;       // needed for the File class

public class StudentDatabase {
    public static final String DATA_FILENAME = "students.txt";

    // We need a throws clause in the header because main() calls
    // a method that creates a Scanner for a file.
    public static void main(String[] args) throws FileNotFoundException {
        Scanner console = new Scanner(System.in);

        boolean done = false;
        while (!done) {
            System.out.print("Enter a major (or \"done\" to exit): ");
            String major = console.nextLine();
            if (major.equals("done")) {
                done = true;
            } else {
                findStudents(major);
            }
        }
    }

    /*
     * findStudents - find all students with the specified major.
     *
     * We put the file processing, including the creation of the Scanner,
     * in this separate method, so each search will start over at the
     * top of the file.
     *
     * We need a throws clause because this method creates a
     * Scanner for a file.
     */
    public static void findStudents(String targetMajor) throws FileNotFoundException {
        Scanner input = new Scanner(new File(DATA_FILENAME));

        boolean found = false;    // have we found any students?

        while (input.hasNextLine()) {
            String record = input.nextLine();
            String[] fields = record.split("\t");

            int id = Integer.parseInt(fields[0]);
            String name = fields[1];
            String major = fields[2];

            if (major.equals(targetMajor)) {
                found = true;
                System.out.println(id + "\t" + name);
            }
        }

        if (!found) {
            System.out.println("No students are majoring in " + targetMajor);
        }
    }
}
