BirthdayPart1.java


Below is the syntax highlighted version of BirthdayPart1.java.


/*************************************************************************
 *  Name:    Donna Gabai 
 *  Login:   dgabai 
 *  Precept: P01
 * 
 *  Compilation:  javac BirthdayPart1.java
 *  Execution:    java BirthdayPart1 int 
 *
 *  Description: input M from command line
 * inputs list of ints representing birthdays from StdIn.
 * outputs how many examined to find M matches.
 *************************************************************************/

public class BirthdayPart1 {

    public static void main(String[] args) {
        // inputs
        int M = Integer.parseInt(args[0]);
        
        // set up array to hold matches for 366 possible birthdays
        int[] bdays = new int[366];
        boolean done = false;        // Did we find M repeats?
        int index = -1;              // Which birthday repeated M times?
        int count = 0;               // how many birthdays read?
        
        // read birthdays until matches found or file exhausted
        while (!done && !StdIn.isEmpty()) {
            int day = StdIn.readInt();
            count++;
            bdays[day]++;
            if (bdays[day] == M) {
                done = true;
                index = day;
            }
        }
        
        // print result
        if (index < 0)
            StdOut.println("No birthday occurs " + M + " times");
        else {
            StdOut.print(count + " birthdays examined to find ");
            StdOut.println(M + " occurrences of " + index);
        }
        
    }
}