Putting it together
- Dart course
- Beginner
- Lesson 23/116
- 6 min
Combine all parts into a working calculator.
Putting it together: menu loop
In the final step we will combine all parts and add a menu loop. A while loop makes the program show the menu again and again.
Structure: var count = 0; while (count < 3) { print('Menu $count'); count++; }. This prints 'Menu 0', 'Menu 1', 'Menu 2'.
In a real calculator the loop reads user input and acts on the choice. Here we will finish with a simple counted loop; reading input is covered in later lessons.
Practice Add the menu loop
Inside main, after the try/catch, add a while loop. Start with var count = 0;; loop with while (count < 3); inside it put print('Menu $count') and count++.
Starter code
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
print(multiply(5, 6));
print(divide(10, 4));
try {
throw Exception('Invalid input');
} catch (e) {
print('Error: $e');
}
// Add a menu with a while loop
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
int multiply(int a, int b) => a * b;
double divide(int a, int b) => a / b;Sample solution
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
print(multiply(5, 6));
print(divide(10, 4));
try {
throw Exception('Invalid input');
} catch (e) {
print('Error: $e');
}
var count = 0;
while (count < 3) {
print('Menu $count');
count++;
}
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
int multiply(int a, int b) => a * b;
double divide(int a, int b) => a / b;Expected output
Calculator ready 7 7 30 2.5 Error: Exception: Invalid input Menu 0 Menu 1 Menu 2
Practice Final calculator
In this final task write the whole program yourself. Inside void main have print('Calculator ready'), an add(3, 4) call, a try/catch and a while loop. Also define the add function.
Starter code
// Write the calculator from scratchSample solution
void main() {
print('Calculator ready');
print(add(3, 4));
try {
throw Exception('Invalid input');
} catch (e) {
print('Error: $e');
}
var count = 0;
while (count < 3) {
print('Menu $count');
count++;
}
}
int add(int a, int b) => a + b;Expected output
Calculator ready 7 Error: Exception: Invalid input Menu 0 Menu 1 Menu 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the best structure for a menu loop?
- for loop
- while loop Correct answer
- if condition
- switch
Explanation: while repeats as long as the condition is true.
2 Loop keyword
____ (true) { showMenu(); }
while (true) { showMenu(); }
Explanation: while sets up a conditional loop.
3 Project parts
| Term | Meaning |
|---|---|
while |
Loop |
add |
Addition |
try/catch |
Error catching |
print |
Output |