Methods, Conditionals, and Loops in Java
Building a Complete Java Program
Structured Program Composition means combining small, understandable operations into a program whose execution you can follow. In Java, a method can calculate one contribution, a conditional can choose that contribution, and a loop can combine many contributions. Your task is to connect these pieces so that the complete program carries out its stated rule, including at boundaries such as the first and last repetitions.
Connect the building blocks
A program's control flow is the order in which its statements execute. Read that order from the active method, rather than simply reading the file from top to bottom. A helper method's declaration describes work that becomes active when the program calls it.
Structure | Role in the complete program | Placement question |
|---|---|---|
Sequence | Performs operations in order | What must happen before the next operation? |
Conditional | Chooses a branch using a true or false condition | Does this decision concern one item or the completed result? |
Loop | Repeats a block while its condition permits | What work belongs to every repetition? |
Method call | Runs a named operation and resumes the caller | How will the caller use the returned result? |
For example, a decision about one round's points belongs in the calculation for that round. A decision about the total points belongs after the total has been completed. Braces make these relationships explicit; indentation helps you see them.
Keep repeated work inside the loop
A variable that stores a running total is an accumulator. For additive contributions, its governing update is:
Initialize the total once before repetition. Add each contribution inside the loop. Use the completed total after the loop. If you reset the total inside the repeated block, earlier contributions disappear.
An iteration includes the work in the loop body. In a basic for loop, initialization happens once, the condition is checked before each iteration, and the update runs after each normally completed iteration. A while loop also checks its condition before its body; its body usually contains an operation that moves the program toward stopping.
Trace the complete program
Example: A club awards two points for an odd-numbered round and four points for an even-numbered round. This complete program totals three rounds.
public class ClubPoints {
static int pointsForRound(int round) {
if (round % 2 == 0) {
return 4;
} else {
return 2;
}
}
static int totalPoints(int rounds) {
int total = 0;
for (int round = 1; round <= rounds; round++) {
total = total + pointsForRound(round);
}
return total;
}
public static void main(String[] args) {
int result = totalPoints(3);
System.out.println(result);
}
}The remainder operation % identifies even rounds because an even integer leaves remainder zero when divided by two. The helper therefore returns 2, 4, and 2 for rounds 1, 2, and 3. The running totals are 2, 6, and 8 points.
The program begins in main. Its call to totalPoints(3) starts the repeated calculation. Each call to pointsForRound finishes before its returned value is added. A return exits the method currently executing, so returning from the helper resumes the calculation inside totalPoints.
The total is returned after the loop finishes. When round becomes 4, the condition is false, and totalPoints returns 8 to main. The program prints 8 once. Here, static allows these methods to be called directly from the static main method.
What to remember
- Give each helper one clear contribution to the complete task.
- Initialize once, update during repetition, and use the completed result afterward.
- Follow calls into helpers and returned values back to their callers.
- Check the first iteration, the last iteration, and the condition that stops repetition.
Example: Planning Snack Tokens for Volunteer Shifts
A community event allocates snack tokens for five volunteer shifts. Shifts 1 and 2 receive three tokens each; later shifts receive five tokens each. The program prints the total allocation and a restocking message. An execution trace records the operations and changing values in the order they actually occur.
public class SnackPlan {
static int tokensForShift(int shift) {
if (shift <= 2) {
return 3;
} else {
return 5;
}
}
static int totalTokens(int shifts) {
int total = 0;
for (int shift = 1; shift <= shifts; shift++) {
total = total + tokensForShift(shift);
}
return total;
}
public static void main(String[] args) {
int total = totalTokens(5);
System.out.println(total);
if (total >= 20) {
System.out.println("Restock");
} else {
System.out.println("Enough");
}
}
}Trace the code without changing it. Complete the call to totalTokens before evaluating the restocking decision in main.
a) What is the running total immediately after shift 3 has been processed?
- Initialize the running total to zero tokens. For shift 1, the helper's condition is true, so its contribution is ________. For shift 2, the condition is still true, so its contribution is ________.
- For shift 3, shift <= 2 is false, so the helper contributes ________. Each returned contribution is added to the existing total.
The running total after shift 3 is 11 tokens. This is an intermediate total; the method has not returned yet.
b) What value does totalTokens(5) return?
- Continue from the 11 tokens accumulated after shift 3. Shift 4 also takes the helper's else branch, so the running total becomes ________.
- Shift 5 contributes ________. Add that contribution to the previous total.
- The loop update changes shift from 5 to 6. The condition shift <= shifts is now 6 <= 5, which is false. Execution continues to the return after the loop.
The method returns 21 tokens. As a check, the first two shifts receive six tokens together, and the remaining three receive fifteen tokens together.
c) What does the complete program print, in order?
- The call to totalTokens(5) returns 21, which becomes the value of total in main. The first print statement therefore prints 21.
- Evaluate the restocking condition using that completed total. The comparison 21 >= 20 evaluates to ________, so execution enters the first branch.
- That branch prints Restock. The else branch is skipped, and no further print statements execute.
The program prints 21 on the first line and Restock on the second line. The helper's return statements supply values to its caller; those statements do not print anything themselves.
A Java program contains the method below, and main later runs the statement int evens = countEvens(9);.
public static int countEvens(int limit) {
int count = 0;
for (int i = 1; i <= limit; i++) {
if (i % 2 == 0) {
count++;
}
}
return count;
}The method's return type is , and the name of its only parameter is . In the call countEvens(9), the value 9 supplied by the caller is called an . During that call the loop body runs times, and the call returns .
A school challenge awards points using the Java methods below. Complete the table for challengeTotal(4), entering exact integers. For each stage, record the helper's returned points and the running total immediately after the addition.
static int stagePoints(int stage) {
if (stage >= 3) {
return 5;
} else {
return 2;
}
}
static int challengeTotal(int stages) {
int total = 0;
for (int stage = 1; stage <= stages; stage++) {
total = total + stagePoints(stage);
}
return total;
}| Stage | Returned points | Running total in points |
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |