šÆ Objective
Create a program that performs arithmetic operations based on command-line arguments with proper error handling and formatted output.
Requirements
- Accept three command-line arguments: first number, operator (+, -, *, /), second number
- Parse the numbers from strings to
double for decimal support
- Use a
switch statement to handle different operators
- Handle division by zero with a clear error message
- Show usage instructions if wrong number of arguments provided
- Format the result to 2 decimal places
- Validate that the operator is one of the supported ones
Expected Output
$ dart run calculator.dart 10 + 5
Result: 10.00 + 5.00 = 15.00
$ dart run calculator.dart 10.5 / 3
Result: 10.50 / 3.00 = 3.50
$ dart run calculator.dart 10 / 0
Error: Division by zero is not allowed.
$ dart run calculator.dart 10 x 5
Error: Invalid operator "x". Supported operators: +, -, *, /
$ dart run calculator.dart
Usage: dart run calculator.dart <number1> <operator> <number2>
Example: dart run calculator.dart 10 + 5
Supported operators: + (addition), - (subtraction), * (multiplication), / (division)
Step-by-Step Hints
š” Hint 1: Argument Validation
Check arguments.length != 3 first. If it's not exactly 3, show usage and exit.
š” Hint 2: Safe Number Parsing
Use double.tryParse(arguments[0]) and double.tryParse(arguments[2]). Check if either returns null before proceeding.
š” Hint 3: Switch Statement
Use switch (arguments[1]) with cases for '+', '-', '*', '/'. Add a default case for invalid operators.
void main(List<String> arguments) {
// Step 1: Validate number of arguments
if (arguments.length != 3) {
print('Usage: dart run calculator.dart ');
print('Example: dart run calculator.dart 10 + 5');
print('Supported operators: + (addition), - (subtraction), * (multiplication), / (division)');
return;
}
// Step 2: Extract arguments
String num1Str = arguments[0];
String operator = arguments[1];
String num2Str = arguments[2];
// Step 3: Convert strings to numbers
double? num1 = double.tryParse(num1Str);
double? num2 = double.tryParse(num2Str);
// Step 4: Validate number conversion
if (num1 == null) {
print('Error: "$num1Str" is not a valid number.');
return;
}
if (num2 == null) {
print('Error: "$num2Str" is not a valid number.');
return;
}
// Step 5: Validate operator
const validOperators = ['+', '-', '*', '/'];
if (!validOperators.contains(operator)) {
print('Error: Invalid operator "$operator".');
print('Supported operators: ${validOperators.join(", ")}');
return;
}
// Step 6: Perform calculation using switch
double? result;
String operationName;
switch (operator) {
case '+':
result = num1 + num2;
operationName = 'Addition';
break;
case '-':
result = num1 - num2;
operationName = 'Subtraction';
break;
case '*':
result = num1 * num2;
operationName = 'Multiplication';
break;
case '/':
if (num2 == 0) {
print('Error: Division by zero is not allowed.');
return;
}
result = num1 / num2;
operationName = 'Division';
break;
default:
print('Error: Unexpected operator.');
return;
}
// Step 7: Display formatted result
print('=== $operationName ===');
print('${num1.toStringAsFixed(2)} $operator ${num2.toStringAsFixed(2)} = ${result!.toStringAsFixed(2)}');
// Step 8: Show additional information
if (result == result.roundToDouble()) {
print('(Result is a whole number)');
}
if (result > 1000000) {
print('(That\'s a big number!)');
} else if (result < 0.01 && result > 0) {
print('(That\'s a very small number!)');
}
// Bonus: Show the calculation in words
print('\nš In words:');
print('${num1Str} ${getOperatorWord(operator)} ${num2Str} equals ${result.toStringAsFixed(2)}');
}
String getOperatorWord(String operator) {
switch (operator) {
case '+': return 'plus';
case '-': return 'minus';
case '*': return 'multiplied by';
case '/': return 'divided by';
default: return operator;
}
}
Challenge: Extend the Project
- Add support for more operations (%, sqrt, pow)
- Allow chaining multiple operations (e.g., 10 + 5 * 2)
- Add a history feature that remembers previous calculations
- Support different number formats (hexadecimal, binary)