Build the Operations
By the end of this lesson, you'll be able to:
- Implement each of the four arithmetic operations as its own path in the code
- Use a switch statement to route to the correct operation based on the operator
- Combine variables and expressions (Modules 3-4) into a working method
Prerequisites: "Plan the Program"
The calculate method
public Decimal calculate(Decimal a, Decimal b, String operator) {
Decimal result;
switch on operator {
when '+' {
result = a + b;
}
when '-' {
result = a - b;
}
when '*' {
result = a * b;
}
when '/' {
result = a / b;
}
}
return result;
}
This is exactly the switch on pattern from Module 6, applied to a real problem: operator is checked once, and the matching arithmetic expression runs.
Trying it out
Calculator calc = new Calculator();
Decimal sum = calc.calculate(12, 5, '+');
System.debug(sum); // 17
Decimal product = calc.calculate(12, 5, '*');
System.debug(product); // 60
Each call passes two numbers and an operator; calculate returns the appropriate result. This is the working core of the calculator — the next two lessons make it safe and presentable.
Why not four separate methods?
You could write add(), subtract(), multiply(), and divide() as four separate methods instead. That's a reasonable design too — but a single calculate method that takes the operator as data is closer to how a real calculator UI works: one button handler that reads whichever operator the user pressed, rather than four different handlers wired up separately.
Full Calculator class so far
public class Calculator {
public Decimal calculate(Decimal a, Decimal b, String operator) {
Decimal result;
switch on operator {
when '+' {
result = a + b;
}
when '-' {
result = a - b;
}
when '*' {
result = a * b;
}
when '/' {
result = a / b;
}
}
return result;
}
}
This is the whole class as it stands after this lesson — one method, one switch statement, four operations. The next lesson adds safety around bad input.
Exercise
Add a fifth case to the switch statement above for the '%' operator (modulo/remainder), using Math.mod(a, b) — note Math.mod requires Integer arguments, so this exercise treats a and b as whole numbers.
Show hint
when '%' { result = Math.mod(a.intValue(), b.intValue()); }
Build the Operations Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
This lesson writes the actual arithmetic: a method that takes two numbers and an operator, and routes to the correct calculation using a switch statement from Module 6.