Putting it together
- Java course
- Beginner
- Lesson 23/116
- 6 min
Write a working calculator with a menu loop.
Putting it together: the for loop
In the final lesson we'll combine the calculator with a for loop. A for loop runs a block of code a fixed number of times.
for (int i = 0; i < 3; i++) {
System.out.println(add(i, i));
}This loop calls add(i, i) for i = 0, 1, 2 and prints the results: 0, 2, 4. We'll cover for in detail in a later group; here we just use it to complete the calculator.
Practice Add a for loop
Add a for (int i = 0; i < 3; i++) loop to main in the existing class. Inside the loop, call println(add(i, i)). Keep the other calls and the try/catch.
Starter code
public class Main {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
return a / b;
}
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println(add(5, 3));
System.out.println(subtract(5, 3));
System.out.println(multiply(5, 3));
try {
System.out.println(divide(10, 2));
} catch (ArithmeticException e) {
System.out.println("Division by zero");
}
}
}Sample solution
public class Main {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
return a / b;
}
public static void main(String[] args) {
System.out.println("Calculator");
for (int i = 0; i < 3; i++) {
System.out.println(add(i, i));
}
System.out.println(subtract(5, 3));
System.out.println(multiply(5, 3));
try {
System.out.println(divide(10, 2));
} catch (ArithmeticException e) {
System.out.println("Division by zero");
}
}
}Expected output
Calculator 0 2 4 2 15 5
Next step
Congratulations! You completed the calculator project. You learned:
- Class and method design
statichelper methods- Defensive zero checks
- Error handling with
try/catch - Repetition with a
forloop
The next groups will deepen operators, strings, conditionals and loops. This project was practice in combining what you learned in a real app.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the main signature
public static ____(String[] args) { }
public static void(String[] args) { }
Explanation: main returns no value.
2 In which order are they written?
- main → class → method → println
- println → main → method → class
- class → method → main → println Correct answer
- method → println → main → class
Explanation: First the class, then methods, then main, last the println calls.
3 Match the project stages
| Term | Meaning |
|---|---|
Class |
Main |
Methods |
add, subtract, multiply, divide |
main |
Entry point |
for |
Loop |