Description
This Node.js program is a simple calculator that takes two numbers and an operator (+, -, *, or /) as input and performs the corresponding operation. The program uses the readline
module to prompt the user for input and performs the calculation based on the operator provided.
Features
- Prompts the user for two numbers and an operator
- Performs addition, subtraction, multiplication, and division based on the operator
- Handles division by zero error
- Displays the result of the calculation
Requirements
- Node.js installed on your system
Code
const readline = require('readline');
// Setup for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to perform calculation
const calculate = (num1, num2, operator) => {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 === 0) {
return 'Error: Division by zero is not allowed.';
}
return num1 / num2;
default:
return 'Invalid operator. Please use +, -, *, or /.';
}
};
// Prompt user for input
rl.question('Enter the first number: ', (firstInput) => {
const num1 = parseFloat(firstInput);
if (isNaN(num1)) {
console.log('Invalid input. Please enter a valid number.');
rl.close();
return;
}
rl.question('Enter the second number: ', (secondInput) => {
const num2 = parseFloat(secondInput);
if (isNaN(num2)) {
console.log('Invalid input. Please enter a valid number.');
rl.close();
return;
}
rl.question('Enter an operator (+, -, *, /): ', (operator) => {
const result = calculate(num1, num2, operator);
console.log(`Result: ${result}`);
rl.close();
});
});
});
Simple Calculator Code
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter first number: ', (num1) => {
rl.question('Enter second number: ', (num2) => {
rl.question('Enter operator (+, -, *, /): ', (operator) => {
let result = eval(`${num1} ${operator} ${num2}`);
console.log(`Result: ${result}`);
rl.close();
});
});
});
Usage
To run the calculator, save the code to a file (e.g., calculator.js
) and execute it using Node.js:
node calculator.js
Follow the prompts to enter two numbers and an operator to perform the calculation.