Project Goal
Build a console-based calculator that supports addition, subtraction, multiplication, division, modulo, and power operations. It reads input from the user, validates it, and shows results in a loop until the user quits.
Design
- A
Calculator class encapsulates operations - A
display() function handles console I/O - Input validation with clear error messages
- History of last 5 calculations
Full Code
import 'dart:io';
import 'dart:math';
class Calculator {
final List<String> _history = [];
double calculate(double a, String op, double b) {
double result = switch (op) {
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => b == 0 ? throw ArgumentError('Division by zero') : a / b,
'%' => b == 0 ? throw ArgumentError('Modulo by zero') : a % b,
'^' => pow(a, b).toDouble(),
_ => throw ArgumentError('Unknown operator: $op'),
};
_history.add('$a $op $b = $result');
if (_history.length > 5) _history.removeAt(0);
return result;
}
void showHistory() {
if (_history.isEmpty) {
print('No history yet.');
return;
}
print('\n--- Last $${_history.length} calculations ---');
_history.asMap().forEach((i, h) => print('$${i + 1}. $h'));
}
}
double? parseNumber(String input) => double.tryParse(input.trim());
void main() {
var calc = Calculator();
print('=== Dart Calculator ===');
print('Operators: + - * / % ^ | Commands: history, quit');
while (true) {
stdout.write('\nEnter expression (e.g. 5 + 3): ');
var input = stdin.readLineSync()?.trim() ?? '';
if (input == 'quit' || input == 'q') {
print('Goodbye!');
break;
}
if (input == 'history') {
calc.showHistory();
continue;
}
var parts = input.split(RegExp(r'\s+'));
if (parts.length != 3) {
print('Invalid format. Use: <number> <operator> <number>');
continue;
}
var a = parseNumber(parts[0]);
var b = parseNumber(parts[2]);
if (a == null || b == null) {
print('Invalid numbers: $${parts[0]}, $${parts[2]}');
continue;
}
try {
var result = calc.calculate(a, parts[1], b);
print('Result: $${result % 1 == 0 ? result.toInt() : result}');
} on ArgumentError catch (e) {
print('Error: $${e.message}');
}
}
}
Running the Project
dart run bin/calculator.dart
# Sample session:
# Enter expression: 10 / 3
# Result: 3.3333333333333335
# Enter expression: 2 ^ 8
# Result: 256
# Enter expression: history
# 1. 10.0 / 3.0 = 3.333...
# 2. 2.0 ^ 8.0 = 256.0
Extension Challenges
- Add trigonometric functions (sin, cos, tan)
- Add parentheses support by writing an expression parser
- Save history to a JSON file and load on startup
- Build a Flutter GUI version of the calculator