Java Tutorial: Build and Test a Study-Plan Calculator - Yenra

Write a small Java command-line program, understand its inputs and output, and test normal and invalid cases.

A navy laptop stands beside ivory stepping blocks leading to a translucent teal module and an amber checkpoint.
Conceptual illustration: build a working program in small steps, with a check at each stage.

A useful first Java program accepts input, does a small calculation and explains the result. This tutorial builds a study-minute calculator: enter one total for each day, then see the number of days, total minutes and daily average. You will also make it reject invalid input and run a small repeatable test.

Prepare one folder and a JDK

You need a plain-text editor, a terminal and a JDK. The examples in this Java guide series were compiled and run with Java 25, without preview features. Check java --version and javac --version; both should identify the JDK you intend to use. If either command is missing or the versions differ, follow the Java setup guide first.

Create an empty folder named study-plan and open a terminal there. Save the program below as StudyPlan.java, including the capital letters. A source file contains the instructions you edit; the compiler produces bytecode that the Java runtime executes. The official getting-started guide explains this compile-and-run cycle.

Download the program, test file and README (ZIP)

Write the program

import java.util.Locale;

public class StudyPlan {
    public static long totalMinutes(String[] values) {
        if (values.length == 0 || values.length > 31) {
            throw new IllegalArgumentException("Enter 1 to 31 daily minute totals.");
        }
        long total = 0;
        for (String value : values) {
            int minutes;
            try {
                minutes = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Use whole minutes: " + value);
            }
            if (minutes < 0 || minutes > 1440) {
                throw new IllegalArgumentException("Each day must be 0 to 1440 minutes.");
            }
            total += minutes;
        }
        return total;
    }

    public static void main(String[] args) {
        try {
            long total = totalMinutes(args);
            System.out.println("Days: " + args.length);
            System.out.println("Total minutes: " + total);
            System.out.printf(Locale.ROOT, "Average minutes/day: %.1f%n",
                    (double) total / args.length);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            System.exit(2);
        }
    }
}

main is the entry point. Its args array holds the space-separated values after the class name. totalMinutes converts each string into a whole number, checks its range and adds it to a running total. The method returns the total so that both the application and a test can use the same calculation.

The exercise accepts 1–31 daily totals, each from 0 to 1,440 minutes. Those are explicit input rules for this small program. Zero is a valid day with no recorded study; including it changes the average. A long stores the total. Casting that total to double before division preserves a fractional average, while %.1f prints one decimal place.

The try/catch block turns a rejected input into a short message and exit code 2. Successful completion returns exit code 0. Locale.ROOT keeps the decimal separator consistent in these examples. For additional language explanations, use the Java language basics and exception-handling lessons.

Compile, run and interpret the result

javac StudyPlan.java
java StudyPlan 25 40 0 35

A successful compilation usually prints nothing and creates StudyPlan.class. Run the class name without an extension. For these invented daily totals, the result is:

Days: 4
Total minutes: 100
Average minutes/day: 25.0

The arithmetic is 25 + 40 + 0 + 35 = 100 minutes, then 100 ÷ 4 = 25.0 minutes per day. The zero-day remains part of the four-day reporting period. If you enter only active days, you are calculating an average per active day instead; decide which question you want the result to answer.

Now run java StudyPlan 20 21. Expect 41 total minutes and an average of 20.5. Change the final value and predict the result before running again. After editing the source, repeat javac StudyPlan.java so that the class file reflects your change.

Test boundaries as well as a normal case

The download includes StudyPlanTest.java. Put it beside the program, then run:

javac StudyPlan.java StudyPlanTest.java
java StudyPlanTest

Expect StudyPlan checks passed. The test calls the calculation directly, checks the total, accepts the upper boundary and rejects missing values, negative minutes, an excessive day total, a decimal and an integer too large to parse. It throws an AssertionError when a check fails; no special JVM assertion flag is required.

On a narrow screen, scroll the table horizontally. Keyboard users can focus the table and use the arrow keys.

Manual checks for the complete command-line program
CommandExpected behaviorReason
java StudyPlan 0One day, zero total and 0.0 averageZero is inside the accepted range.
java StudyPlanInput-count message; exit code 2An average needs a reporting period.
java StudyPlan -1Range message; exit code 2Daily minutes must be nonnegative.
java StudyPlan 2.5Whole-minutes message; exit code 2This input format uses integers.

In PowerShell, inspect the previous process result with $LASTEXITCODE; in a Unix shell use echo $?. Check it immediately after the Java command. These manual checks cover messages and process behavior, while the supplied test concentrates on calculation and validation.

Fix a failure, then extend one behavior

On a narrow screen, scroll the table horizontally. Keyboard users can focus the table and use the arrow keys.

Common first-program problems
SymptomWhat to inspectUseful correction
Compiler command unavailableSelected JDK and terminal PATHUse the setup guide, then open a terminal with that JDK available.
Public class must be in its own fileActual filename, including hidden extensionsSave plain text as StudyPlan.java, not StudyPlan.java.txt.
Could not find main classWorking folder and successful compilationRun from the folder containing StudyPlan.class, or use java -cp followed by that folder.
Output still shows an old changeWhether the edited source was recompiledCompile again and check the terminal folder.

For a small extension, print total hours as well as minutes. Use total / 60.0, choose a clear rounding format and label the unit. For the 100-minute example, two decimal places should show 1.67 hours. Keep the original minute total so a reader can recover the exact input sum.

A second exercise is to report the largest daily total. Start from an actual input value, update the maximum while iterating, and test an all-zero period. Add one behavior at a time and rerun the earlier checks. That habit becomes especially valuable when the program grows to use collections, files or a database.

Continue with a related task