I have created a JavaScript simple calculator using the 'readline-sync' library for Node.js to handle terminal input/output. The calculator asks the user which operation they would like to perform (+, -, *, /). After they have selected an operation, it asks for two numbers. It performs the calculation and displays the result e.g. 45+9 = 54. After it displays the result, it should ask if the user wants to perform another calculation. How do I add a loop to allow the user to continue using the calculator until they choose to exit?
Here's my code so far:
const calculator = require('readline-sync');
let operations = ['+', '-', '*', '/'];
let index = null;
let operator = null;
let firstNumber = 0;
let secondNumber = 0;
// Gets the operation question and the options
function operationQuestion(){
operator = calculator.question("What operation would you like to perform?"
+'\nOptions:'
+'\nAddition ('+ operations[0]+')'
+'\nSubtraction ('+ operations[1]+')'
+'\nMultiplication ('+ operations[2]+')'
+'\nDivision ('+ operations[3]+')\n'
);
if (!operations.includes(operator)) {
console.log("That is not a valid operation");
operationQuestion();
}
// Gets the first and second number
firstNumber = calculator.questionInt("Type the first number: ");
secondNumber = calculator.questionInt("Type the second number: ");
// 4 of the operations
switch(operator) {
case '+':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber + secondNumber));
break;
case '-':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber - secondNumber));
break;
case '*':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber * secondNumber));
break;
case '/':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber / secondNumber));
break;
default:
console.log("Something went wrong :(");
}
}
// Logic
operationQuestion();
input = calculator.question("Do you want to perform another calculation?")
I have created a JavaScript simple calculator using the 'readline-sync' library for Node.js to handle terminal input/output. The calculator asks the user which operation they would like to perform (+, -, *, /). After they have selected an operation, it asks for two numbers. It performs the calculation and displays the result e.g. 45+9 = 54. After it displays the result, it should ask if the user wants to perform another calculation. How do I add a loop to allow the user to continue using the calculator until they choose to exit?
Here's my code so far:
const calculator = require('readline-sync');
let operations = ['+', '-', '*', '/'];
let index = null;
let operator = null;
let firstNumber = 0;
let secondNumber = 0;
// Gets the operation question and the options
function operationQuestion(){
operator = calculator.question("What operation would you like to perform?"
+'\nOptions:'
+'\nAddition ('+ operations[0]+')'
+'\nSubtraction ('+ operations[1]+')'
+'\nMultiplication ('+ operations[2]+')'
+'\nDivision ('+ operations[3]+')\n'
);
if (!operations.includes(operator)) {
console.log("That is not a valid operation");
operationQuestion();
}
// Gets the first and second number
firstNumber = calculator.questionInt("Type the first number: ");
secondNumber = calculator.questionInt("Type the second number: ");
// 4 of the operations
switch(operator) {
case '+':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber + secondNumber));
break;
case '-':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber - secondNumber));
break;
case '*':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber * secondNumber));
break;
case '/':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber / secondNumber));
break;
default:
console.log("Something went wrong :(");
}
}
// Logic
operationQuestion();
input = calculator.question("Do you want to perform another calculation?")
Share
Improve this question
asked Mar 31 at 15:50
Ruby PepperRuby Pepper
114 bronze badges
New contributor
Ruby Pepper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
- Please show us your attempt at implementing this. – 0stone0 Commented Mar 31 at 15:53
- That's some weird way to indent code. Why not stick with common practice? – trincot Commented Mar 31 at 15:54
- 1 NB: the current code has issues: it uses recursion in a bad way: if you enter a wrong response, then after you give a correct response, it will again ask for operands a second time, and then print "Something went wrong". Maybe you should first make sure the code you already have is working correctly, before thinking of extending it. – trincot Commented Mar 31 at 15:56
2 Answers
Reset to default 0I have refactored the code to make it better. It is tested and works fine:
const calculator = require('readline-sync');
// Gets the operation question and the options
function operationQuestion(){
const operations = ['+', '-', '*', '/'];
while (true){
const operator = calculator.question("What operation would you like to perform?"
+'\nOptions:'
+'\nAddition ('+ operations[0]+')'
+'\nSubtraction ('+ operations[1]+')'
+'\nMultiplication ('+ operations[2]+')'
+'\nDivision ('+ operations[3]+')\n'
);
if (!operations.includes(operator)) {
console.log("That is not a valid operation");
operationQuestion();
}
// Gets the first and second number
const {firstNumber, secondNumber} = promptForInput(calculator);
const result = calculate({firstNumber,secondNumber,operator})
logResults({firstNumber, secondNumber, operator, result});
if(!checkIfToRecalculate(calculator)){
break
}
}
}
const promptForInput = (calculator)=>{
firstNumber = calculator.questionInt("Type the first number: ");
secondNumber = calculator.questionInt("Type the second number: ");
return {firstNumber, secondNumber}
}
const calculate = ({firstNumber, secondNumber,operator})=>{
if (operator === '+') return firstNumber + secondNumber;
if (operator === '-') return firstNumber - secondNumber;
if (operator === '*') return firstNumber * secondNumber;
if (operator === '/') return firstNumber / secondNumber;
}
const logResults = ({firstNumber, secondNumber,operator, result})=>{
console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${result}`);
}
const checkIfToRecalculate = (calculator)=>{
const validInputs = ['y', 'yes', 'no', 'n', 'exit']
let operator = calculator.question("Do you want to perform another calculation?")
while(!validInputs.includes(operator)){
console.log(`${operator} is invalid, enter any of ${validInputs.join(',')}`)
operator = calculator.question("Do you want to perform another calculation?")
}
if (operator.toLowerCase() === 'y' || operator.toLowerCase() === 'yes'){
return true
}
return false
}
operationQuestion();
First of all we want to use a while loop to repeatedly ask the user if they want to perform another calculation. Then check user input after each calculation to determine whether to continue or exit.
const calculator = require('readline-sync');
let operations = ['+', '-', '*', '/'];
function operationQuestion() {
let operator, firstNumber, secondNumber;
while (true) { // Infinite loop, will break if user chooses to exit
// Ask for operation
operator = calculator.question(
"What operation would you like to perform?" +
"\nOptions:" +
"\nAddition (" + operations[0] + ")" +
"\nSubtraction (" + operations[1] + ")" +
"\nMultiplication (" + operations[2] + ")" +
"\nDivision (" + operations[3] + ")\n"
);
if (!operations.includes(operator)) {
console.log("That is not a valid operation. Please try again.");
continue; // Restart loop if invalid operator
}
// Get numbers from user
firstNumber = calculator.questionInt("Type the first number: ");
secondNumber = calculator.questionInt("Type the second number: ");
// Perform calculation
switch (operator) {
case '+':
console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${firstNumber + secondNumber}`);
break;
case '-':
console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${firstNumber - secondNumber}`);
break;
case '*':
console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${firstNumber * secondNumber}`);
break;
case '/':
if (secondNumber === 0) {
console.log("Error: Division by zero is not allowed.");
} else {
console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${firstNumber / secondNumber}`);
}
break;
default:
console.log("Something went wrong :(");
}
// Ask if the user wants to perform another calculation
let input = calculator.question("Do you want to perform another calculation? (yes/no): ").toLowerCase();
if (input !== 'yes' && input !== 'y') {
console.log("Goodbye!");
break; // Exit loop if user does not want another calculation
}
}
}