Popcorn Hack 1

/**
 * Calculates the sum of all positive even integers in the given array.
 * <p>
 * The method iterates through each element of the {@code nums} array and adds it to a running total
 * only if the element is greater than zero and evenly divisible by two. The method then returns
 * the final sum.
 * </p>
 *
 * <p><b>Preconditions:</b></p>
 * <ul>
 *   <li>{@code nums} must not be {@code null}.</li>
 *   <li>{@code nums} may contain any integer values (positive, negative, or zero).</li>
 * </ul>
 *
 * <p><b>Postconditions:</b></p>
 * <ul>
 *   <li>Returns the sum of all positive even numbers in {@code nums}.</li>
 *   <li>If there are no positive even numbers, returns {@code 0}.</li>
 * </ul>
 *
 * @param nums an array of integers to evaluate
 * @return the sum of all positive even integers in {@code nums}; {@code 0} if none exist
 *
 * <p><b>Example:</b></p>
 * <pre>
 * int[] numbers = {1, 2, 3, 4, -6};
 * int result = doSomething(numbers);  // result = 6
 * </pre>
 */
public static int doSomething(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] > 0 && nums[i] % 2 == 0) {
            result += nums[i];
        }
    }
    return result;
}

// Example test to verify output
int[] testArray = {1, 2, 3, 4, -6};
System.out.println(doSomething(testArray));  // Expected output: 6

6

Popcorn Hack 2


/**
 * Manages student grades and calculates final grades based on weighted categories.
 * <p>
 * This class allows teachers or students to track assignments across different categories
 * (such as homework, tests, and projects) and compute a final grade using category weights.
 * It can also handle extra credit and generate a summary report of all recorded data.
 * </p>
 *
 * <p><b>Key Features:</b></p>
 * <ul>
 *   <li>Store assignments organized by category</li>
 *   <li>Apply custom weights to each grade category</li>
 *   <li>Track and include extra credit points</li>
 *   <li>Generate formatted grade reports</li>
 * </ul>
 *
 * <p><b>Usage Example:</b></p>
 * <pre>
 * GradeBook myGrades = new GradeBook();
 * myGrades.setCategoryWeight("Homework", 0.30);
 * myGrades.setCategoryWeight("Tests", 0.70);
 * myGrades.addAssignment("Homework", "HW1", 95.0);
 * myGrades.addAssignment("Tests", "Unit Test 1", 88.0);
 * double finalGrade = myGrades.calculateFinalGrade();
 * System.out.println("Final Grade: " + finalGrade);
 * </pre>
 *
 * @author Ahaan
 * @version 1.0
 * @since 2025-10-06
 */
public class GradeBook {
    private HashMap<String, Double> assignments;
    private HashMap<String, Double> categoryWeights;
    private double extraCredit;

    /**
     * Adds an assignment score to a specific category.
     *
     * <p><b>Preconditions:</b></p>
     * <ul>
     *   <li>{@code category} and {@code name} must not be {@code null}.</li>
     *   <li>{@code score} should typically be between 0 and 100.</li>
     * </ul>
     *
     * <p><b>Postconditions:</b></p>
     * <ul>
     *   <li>The assignment is stored under the specified category.</li>
     * </ul>
     *
     * @param category the category name (e.g., "Homework", "Tests")
     * @param name the assignment name
     * @param score the score earned (0–100)
     */
    public void addAssignment(String category, String name, double score) { }

    /**
     * Sets the weight for a specific grade category.
     *
     * <p><b>Preconditions:</b></p>
     * <ul>
     *   <li>{@code category} must not be {@code null}.</li>
     *   <li>{@code weight} should be between 0.0 and 1.0.</li>
     * </ul>
     *
     * <p><b>Postconditions:</b></p>
     * <ul>
     *   <li>The specified weight is stored for that category.</li>
     * </ul>
     *
     * @param category the category name
     * @param weight the weight as a decimal (e.g., 0.30 for 30%)
     */
    public void setCategoryWeight(String category, double weight) { }

    /**
     * Calculates the final weighted grade including any extra credit.
     *
     * <p><b>Postconditions:</b></p>
     * <ul>
     *   <li>Returns a final numeric grade between 0 and 100 (or higher if extra credit applies).</li>
     * </ul>
     *
     * @return the final grade as a percentage
     */
    public double calculateFinalGrade() { return 0.0; }

    /**
     * Generates a formatted text report of all assignments, categories, and weights.
     *
     * @return a formatted {@code String} containing the grade report
     */
    public String generateReport() { return ""; }
}

Homework Hacks

Part 1 Documentation Analysis

Improved Code

/**
 * Demonstrates a simple example of adding two integers and displaying the result.
 * <p>
 * This program defines a method {@code add(int, int)} that returns the sum of two integers,
 * and calls it from the {@code main} method to print the result to the console.
 * </p>
 *
 * <p><b>Example Output:</b></p>
 * <pre>
 * ans is 15
 * </pre>
 *
 * @author Ahaan
 * @version 1.0
 * @since 2025-10-07
 */
public class Stuff {

    /**
     * The main entry point of the program.
     * Initializes two integers, adds them, and prints the result.
     *
     * @param args command-line arguments (not used)
     */
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = add(x, y);
        System.out.println("ans is " + z);
    }

    /**
     * Adds two integers and returns their sum.
     *
     * <p><b>Preconditions:</b></p>
     * <ul>
     *   <li>Inputs {@code a} and {@code b} are valid integers.</li>
     * </ul>
     *
     * <p><b>Postconditions:</b></p>
     * <ul>
     *   <li>Returns the arithmetic sum of {@code a} and {@code b}.</li>
     * </ul>
     *
     * @param a the first integer
     * @param b the second integer
     * @return the sum of {@code a} and {@code b}
     */
    static int add(int a, int b) {
        return a + b;
    }
}

Explanation

I Added Javadoc comments for the class and both methods, used proper class name capitalization, added @param and @return tags for method documentation, provided an example output and clear descriptions of purpose, and I also improved the legibility with correct naming connventions.

Part 2 Document a Complex Method

/**
 * Attempts to enroll a student in a specific course for a given semester.
 * <p>
 * This method checks for various conditions such as course availability,
 * schedule conflicts, prerequisite completion, and credit limits before
 * enrolling the student. If all checks pass, the student and course records
 * are updated, and the enrollment transaction is recorded.
 * </p>
 *
 * <p><b>Preconditions:</b></p>
 * <ul>
 *   <li>The student and course records exist in the system.</li>
 *   <li>The semester value is valid (e.g., Fall = 1, Spring = 2).</li>
 * </ul>
 *
 * <p><b>Postconditions:</b></p>
 * <ul>
 *   <li>The student is added to the course roster and the course is added to the student’s schedule, if successful.</li>
 *   <li>A transaction record is created for the enrollment.</li>
 *   <li>If any condition fails, the enrollment is not processed and {@code false} is returned.</li>
 * </ul>
 *
 * @param studentId the unique identifier of the student attempting to enroll
 * @param courseCode the unique code identifying the course
 * @param semester the semester number in which the enrollment occurs
 * @return {@code true} if enrollment succeeds; {@code false} otherwise
 */
public boolean enrollStudent(String studentId, String courseCode, int semester) {
    Student student = findStudentById(studentId);
    if (student == null) return false;

    Course course = findCourseByCode(courseCode);
    if (course == null) return false;

    if (course.isFull()) return false;
    if (student.hasScheduleConflict(course)) return false;
    if (!student.hasPrerequisites(course)) return false;
    if (student.getCreditHours() + course.getCreditHours() > 18) return false;

    student.addCourse(course);
    course.addStudent(student);
    recordEnrollmentTransaction(studentId, courseCode, semester);
    return true;
}

Part 3 Reflection Questions

Even if they didn’t write the code, documentation guarantees that everyone on the team is aware of how it operates. It makes sure long-term maintainability, expedites the onboarding of new members in understanding a project, and helps prevent duplication of effort. Someone might be able to remeber what they wrote in a project they made on your own, but in a team project, the documentation becomes something that anyone can remeber and understand. Documentation should be used when you are doing a complex and less obvious coding task, so people can understand what you are doing. You shouldn’t use documentation for simplier concepts or tasks, the documentation would not be needed in this scenario.

Extra Credit

Challenge 1 Document a Recursive Method

/**
 * Computes the factorial of a non-negative integer recursively.
 * <p>
 * The factorial of a number {@code n} is defined as:
 * {@code n! = n × (n - 1) × ... × 1}, with the base case {@code 0! = 1}.
 * </p>
 *
 * <p><b>Base Case:</b> If {@code n == 0}, return 1.</p>
 * <p><b>Recursive Case:</b> If {@code n > 0}, return {@code n * factorial(n - 1)}.</p>
 *
 * <p><b>Time Complexity:</b> O(n)</p>
 * <p><b>Space Complexity:</b> O(n) due to recursion stack</p>
 *
 * @param n the number to compute factorial for (must be non-negative)
 * @return the factorial of {@code n}
 * @throws IllegalArgumentException if {@code n} is negative
 *
 * <p>Example:</p>
 * <pre>
 * int result = factorial(5);  // returns 120
 * </pre>
 */
public static int factorial(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("n must be non-negative");
    }
    if (n == 0) return 1;  // base case
    return n * factorial(n - 1);  // recursive case
}

// --- Test / Output ---
int testValue = 5;
System.out.println("Factorial of " + testValue + " is: " + factorial(testValue));

Factorial of 5 is: 120

Challenge 2 Team Documentation Standard

Document:

  • Public classes and methods
  • Anything that’s tricky, like recursive stuff or complex algorithms
  • Methods that change data, save files, talk to databases, etc.
  • Anything other people will actually use

Don’t need documenting:

  • Private helper methods that are super simple
  • Getters/setters that just return or set a value
  • Code that’s obvious (no need to write “adds 1 to x”)

JavaDoc Tags Guide

Public Methods

  • @param → what the inputs mean
  • @return → what it gives back
  • @throws → any errors it might throw
  • @since → when it was added
  • @version → version number

Classes

  • @author
  • @version
  • @since
  • Maybe a short example usage

Private / Simple Methods

  • Optional comment only if it will help

Challenge 3 Team Documentation Standard

Before

public double calculateTotal(List<Item> items) {
    double total = 0;
    for (Item item : items) {
        total += item.getPrice();
    }
    return total;
}

After

/**
 * Calculates the total price of all {@link Item} objects in the specified list.
 * <p>
 * This method iterates over each {@link Item} in the provided collection and
 * accumulates their individual prices using {@link Item#getPrice()}. The total
 * value represents the combined monetary amount of all items in the list.
 * </p>
 *
 * <p>
 * This method assumes that:
 * <ul>
 *   <li>Each {@link Item} object provides a valid, non-negative price value.</li>
 *   <li>The {@code items} list does not contain {@code null} elements.</li>
 *   <li>The method performs a simple summation and does not handle currency
 *       formatting, discounts, or taxes.</li>
 * </ul>
 * </p>
 *
 * <h3>Example Usage:</h3>
 * <pre>{@code
 * List<Item> cart = List.of(
 *     new Item("Book", 12.99),
 *     new Item("Pen", 2.49),
 *     new Item("Notebook", 5.99)
 * );
 *
 * double total = calculateTotal(cart);
 * System.out.printf("Total price: %.2f%n", total);
 * // Output: Total price: 21.47
 * }</pre>
 *
 * <h3>Performance Notes:</h3>
 * <p>
 * The runtime complexity of this method is O(n), where n is the number of
 * elements in the {@code items} list. It performs a single linear traversal
 * and uses constant extra space.
 * </p>
 *
 * @param items a list of {@link Item} objects whose prices will be totaled;
 *              must not be {@code null}
 * @return the sum of all item prices as a {@code double}; returns 0.0 if the list is empty
 * @throws NullPointerException if {@code items} is {@code null}
 *
 * @see Item
 * @see Item#getPrice()
 */
public double calculateTotal(List<Item> items) {
    double total = 0;
    for (Item item : items) {
        total += item.getPrice();
    }
    return total;
}