Popcorn Hack 1
/**
* Returns the sum of all positive, even integers in the provided array.
* @param nums an array of integers to evaluate (must not be {@code null})
* @return the sum of all positive even integers in {@code nums}; {@code 0} if none exist
* @throws NullPointerException if {@code nums} is {@code null}
*/
public int doSomething(int[] nums) {
// Defensive check: caller must supply a non-null array.
// Throwing a NullPointerException makes the precondition explicit.
if (nums == null) {
throw new NullPointerException("nums must not be null");
}
// Accumulator for the sum of positive even numbers found in the array.
int result = 0;
// Loop over each element of the array by index.
for (int i = 0; i < nums.length; i++) {
// Check two conditions:
// 1) nums[i] > 0 ensures the number is positive.
// 2) nums[i] % 2 == 0 ensures the number is even.
// Only values that satisfy both are added to the accumulator.
if (nums[i] > 0 && nums[i] % 2 == 0) {
result += nums[i];
}
}
// Return the computed sum. If no positive even numbers were found, result is 0.
return result;
}
Popcorn Hack 2
import java.util.HashMap;
/**
* Simple GradeBook for storing assignment scores by category and computing a weighted grade.
* <p>
* Purpose: Record assignments, set category weights, add extra credit, compute a final grade,
* and produce a short text report.
* </p>
*
* <p><b>Key methods:</b> {@link #addAssignment}, {@link #setCategoryWeight},
* {@link #calculateFinalGrade}, {@link #generateReport}.</p>
*
* <p><b>Example:</b>
* <pre>
* GradeBook gb = new GradeBook();
* gb.setCategoryWeight("Homework", 0.3);
* gb.addAssignment("Homework","HW1", 95.0);
* double grade = gb.calculateFinalGrade();
* </pre>
* </p>
*
* @author Nora Ahadian
* @version 1.0
* @since 1.0
*/
public class GradeBook {
private HashMap<String, Double> assignments;
private HashMap<String, Double> categoryWeights;
private double extraCredit;
/**
* Add or replace an assignment score in the given category.
* <p>
* Precondition: {@code category} and {@code name} are non-null/non-empty.
* Postcondition: The assignment {@code category:name} is stored with {@code score}.
* </p>
*
* @param category assignment category (e.g., "Exams")
* @param name assignment name (e.g., "Midterm1")
* @param score numeric score (commonly 0–100)
*/
public void addAssignment(String category, String name, double score) { }
/**
* Set or update the weight for a category.
* <p>
* Precondition: {@code category} non-null/non-empty; {@code weight} >= 0.
* Postcondition: {@code categoryWeights} contains the provided weight.
* </p>
*
* @param category category name
* @param weight relative weight (e.g., 0.25 for 25%)
*/
public void setCategoryWeight(String category, double weight) { }
/**
* Compute the final weighted grade (0–100 scale) using category averages and weights,
* then add {@code extraCredit}.
* <p>
* If category weights do not sum to 1.0, weights are applied proportionally.
* </p>
*
* @return final grade (may be >100 if extra credit pushes it above 100)
*/
public double calculateFinalGrade() { return 0.0; }
/**
* Produce a short human-readable report listing categories, assignments, weights,
* and the computed final grade.
*
* @return multi-line report as a String
*/
public String generateReport() { return ""; }
}
Homework Hack
Part 1
/**
* AddDemo — small program that adds two integers and prints the result.
*
* <p>Purpose: Demonstrates a minimal, well-documented Java program with a reusable
* {@link #add(int,int)} method and a clear {@code main} entry point.</p>
*
* @author Example Author
* @version 1.0
* @since 1.0
*/
public class AddDemo {
/**
* Application entry point. Creates two integers, computes their sum using
* {@link #add(int,int)}, and prints the result to standard output.
*
* @param args command-line arguments (not used)
*/
public static void main(String[] args) {
int x = 5;
int y = 10;
// compute the sum of x and y
int z = add(x, y);
// print the result
System.out.println("ans is " + z);
}
/**
* Returns the arithmetic sum of two integers.
*
* <p><b>Preconditions:</b> none (method accepts any int values).</p>
* <p><b>Postconditions:</b> returns {@code a + b}. Note that if the mathematical
* sum exceeds the range of {@code int}, standard two's-complement overflow will occur.</p>
*
* @param a the first addend
* @param b the second addend
* @return the sum of {@code a} and {@code b}
*/
public static int add(int a, int b) {
return a + b;
}
}
What I Changed:
Renamed the class to follow Java naming conventions (AddDemo instead of stuff). Added clear Javadoc for the class, main, and add with purpose, parameters, pre/postconditions, version, and author. Improved formatting and spacing for readability and maintainability.
Part 2
/**
* Attempts to enroll a student in a course for a given semester.
* <p>
* This method performs a sequence of validations and, if they all succeed,
* updates in-memory objects and records the enrollment transaction:
* <ol>
* <li>Looks up the {@code Student} by {@code studentId} and the {@code Course}
* by {@code courseCode}.</li>
* <li>Checks that the course is not full, the student has no schedule conflict,
* the student meets prerequisites, and adding the course will not push the
* student's semester credit total above 18 hours.</li>
* <li>If all checks pass, the course is added to the student's schedule,
* the student is added to the course roster, and an enrollment transaction
* is recorded for the given {@code semester}.</li>
* </ol>
* </p>
*
* <p><b>Preconditions / caller expectations:</b></p>
* <ul>
* <li>{@code studentId} and {@code courseCode} are expected to identify existing records.
* If either lookup fails, the method returns {@code false}.</li>
* <li>{@code semester} should represent a valid semester identifier in the calling context.
* (This method will not validate semester semantics beyond passing it to
* {@code recordEnrollmentTransaction}.)</li>
* </ul>
*
* <p><b>Postconditions:</b></p>
* <ul>
* <li>If the method returns {@code true}:
* <ul>
* <li>The student object contains the new course (via {@code student.addCourse(course)}).</li>
* <li>The course object contains the student (via {@code course.addStudent(student)}).</li>
* <li>An enrollment transaction has been recorded by
* {@code recordEnrollmentTransaction(studentId, courseCode, semester)}.</li>
* </ul>
* </li>
* <li>If the method returns {@code false}:
* <ul>
* <li>No modifications to {@code student} or {@code course} are performed by this
* method (all failure checks occur before any mutation).</li>
* </ul>
* </li>
* </ul>
*
* <p><b>Failure reasons (method returns {@code false} when any of the following occur):</b></p>
* <ul>
* <li>No student found for {@code studentId}.</li>
* <li>No course found for {@code courseCode}.</li>
* <li>The course is already full ({@code course.isFull() == true}).</li>
* <li>The student has a schedule conflict with the course
* ({@code student.hasScheduleConflict(course) == true}).</li>
* <li>The student is missing one or more prerequisites
* ({@code student.hasPrerequisites(course) == false}).</li>
* <li>Adding the course would cause the student's credit hours to exceed 18
* ({@code student.getCreditHours() + course.getCreditHours() > 18}).</li>
* </ul>
*
* <p><b>Side effects:</b> On success the method mutates both the {@code Student}
* and {@code Course} objects and records a transaction. Callers should ensure
* that any required persistence/transaction boundaries are handled if these
* objects are backed by a database. This method is not explicitly thread-safe;
* concurrent calls may require external synchronization.</p>
*
* <p><b>Example:</b></p>
* <pre>
* boolean ok = enrollStudent("s12345", "CS101", 20251);
* if (ok) {
* // enrollment succeeded
* } else {
* // enrollment failed (inspect reasons via application UI/logs)
* }
* </pre>
*
* @param studentId unique identifier of the student to enroll
* @param courseCode unique course code to enroll the student in
* @param semester integer representing the semester (caller-defined format)
* @return {@code true} if enrollment succeeded and changes were applied; {@code false}
* if enrollment failed for any validation reason (no changes applied)
*/
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;
}
What I changed
I renamed the class to follow Java conventions, cleaned up formatting/spacing, and added short inline comments in main for clarity. I also added clear Javadoc for the class and both methods (including pre/postconditions and an overflow note) and made add explicitly public static so it’s reusable.
Part 3
Why documentation matters more on teams
Documentation provides a shared contract and history: when many people touch the same codebase, clear docs make intentions, assumptions, and side effects explicit so teammates can use, review, and maintain code without asking the original author. In solo projects you can often rely on memory or local context, but in teams docs speed onboarding, reduce miscommunication, and prevent subtle bugs caused by wrong assumptions.
When to document vs when not to
Should document: public or non-trivial methods (for example, enrollStudent(…)) that have validations, side effects, update multiple objects, interact with external systems, or rely on non-obvious business rules — include preconditions, postconditions, and failure modes. Should not document: tiny, self-explanatory private helpers or trivial getters/setters (e.g., int add(int a,int b){ return a+b; }) where the code is obvious and comments would just repeat the implementation.