Home > database >  keep asking user for input in javascript
keep asking user for input in javascript

Time:03-14

I am working on a javascript code and I am learning it for the first time I want to create a calculator and it should keep asking user for numbers and providing output until the user enters a specific number instead of number 1

The code:

<html>
<head>
    <title>Calculator</title>
</head>
<body>
    <script>
        const operator = prompt('Enter operator ( either  , -, * or / ): ');

// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));

let result;
if(number1 == '-999'){
    document.write('The program is terminated');
}
else if (operator == ' ') {
    result = number1   number2;
}
else if (operator == '-') {
    result = number1 - number2;
}
else if (operator == '*') {
    result = number1 * number2;
}
else {
    result = number1 / number2;
}

document.write(`${number1} ${operator} ${number2} = ${result}`);
    </script>
</body>
</html>

CodePudding user response:

Create a while True loop and break out of it if if -999 is entered.

while (true) {
        const operator = prompt('Enter operator ( either  , -, * or / ): ');

        // take the operand input
        const number1 = parseFloat(prompt('Enter first number: '));
        const number2 = parseFloat(prompt('Enter second number: '));

        let result;
        if(number1 == '-999'){
            document.write('The program is terminated');
            break;
        }
        else if (operator == ' ') {
            result = number1   number2;
        }
        else if (operator == '-') {
            result = number1 - number2;
        }
        else if (operator == '*') {
            result = number1 * number2;
        }
        else {
            result = number1 / number2;
        }
        document.write(`${number1} ${operator} ${number2} = ${result}`);
        document.write("<br>");
}

CodePudding user response:

This is not a direct answer but more of a preview of the sort of thing you'll be writing when you start making user interfaces in HTML rather than using modal dialogs.

It does demonstrate how to use a while loop to handle multiple values (which translates to multiple prompts in the case of your current interface).

//Identifies DOM elements, and defines an array and an error string
const 
  operatorSelect = document.getElementById("operator-select"),
  numberInput = document.getElementById("number-input"),
  enterButton = document.getElementById("enter-button"),
  calculateButton = document.getElementById("calculate-button"),
  resultDiv = document.getElementById("result-div"),
  numbersArray = [],
  DIV0_ERR = "Can't divide by zero";

// Calls `enter` or `calculate` whenever corresponding button is clicked
enterButton.addEventListener("click", enter);
calculateButton.addEventListener("click", calculate);

function enter(){

  // Adds number to array, resets input, and clears resultDiv if necessary
  const number = parseFloat(numberInput.value);
  numbersArray.push(number);
  numberInput.value = 0;
  resultDiv.textContent = "";
}

function calculate(){
  // Returns early if no numbers have been entered
  if(numbersArray.length === 0){
    return;
  }
  // Gets operator and first number, and prepares to loop through array
  let
    operator = operatorSelect.value,
    resultSoFar = numbersArray[0],
    currentIndex = 0,
    currentNumber;

  // Each iteration: increments index, gets number, updates `resultSoFar`
  while(  currentIndex < numbersArray.length){
    currentNumber = numbersArray[currentIndex];
    resultSoFar = doOperation(operator, resultSoFar, currentNumber);
  }
  // Clears numbers Array and resets input
  numbersArray.length = 0;
  numberInput.value = 0;

  // Returns most recent result from `doOperation`
  resultDiv.textContent = resultSoFar;
}

function doOperation(op, num1, num2){
  // Performs operation based on operator (or returns error string)
  if(num1 === DIV0_ERR){ return DIV0_ERR; }
  if(op === " "){ return num1   num2; }
  if(op === "-"){ return num1 - num2; }
  if(op === "*"){ return num1 * num2; }
  if(op === "/"){ return (num2 === 0) ? DIV0_ERR : (num1 / num2); }
}
select, input, button, div{ display: block; width: 8rem; }
#operator-select, #calculate-button{ margin: 1rem 0; }
#result-div{ text-align: center; font-size: 1.8rem; }
Select an operation, enter numbers, then click "CALCULATE"
<select id="operator-select">
    <option> </option>
    <option>-</option>
    <option>*</option>
    <option>/</option>
</select>
<input type="number" id="number-input" value = "0" />
<button id="enter-button">ENTER</button>
<button id="calculate-button">CALCULATE</button>
<div id="result-div"></div>

  • Related