Home > Software design >  result appearing twice in calculator
result appearing twice in calculator

Time:06-30

hi everyone i am jonnathan i am trying to create a calculator in javascript and i am following a tutorial on youtube but for some reason if i add 1 and 1 together the result 2 is alerting

var number1 = prompt("Input the first number");
var op = prompt("Input operator")
var number2 = prompt("Input 3rd number")

if (op == " ") {
  if (number1 == "1") {
    if (number2 == "1") {
      alert("2");
    }
    if (number2 == "2") {
      alert("3");
    }
    if (number2 == "3") {
      alert("4");
    }
    if (number2 == "4") {
      alert("5");
    }
    if (number2 == "5") {
      alert("6");
    }
    if (number2 == "6") {
      alert("7");
    }
    if (number2 == "7") {
      alert("8");
    }
    if (number2 == "8") {
      alert("9");
    }
    if (number2 == "9") {
      alert("10");
    }
  }
  if (number2 == "1") {
    if (number1 == "1") {
      alert("2");
    }
    if (number1 == "2") {
      alert("3");
    }
    if (number1 == "3") {
      alert("4");
    }
    if (number1 == "4") {
      alert("5");
    }
    if (number1 == "5") {
      alert("6");
    }
    if (number1 == "6") {
      alert("7");
    }
    if (number1 == "7") {
      alert("8");
    }
    if (number1 == "8") {
      alert("9");
    }
    if (number1 == "9") {
      alert("10");
    }
  }
}

twice there are no errors in the console either that i think could help me with this issue

so far the calculator only adds numbers and only does it through 1 ti 9. how can i fix this error?

CodePudding user response:

In your code:

if (op == " ") {
    if (number1 == "1")
    {
        if (number2 == "1")
        {
            alert("2");
        }

This section is alerting "2" first. And then this section:

if (number2 == "1") {
    if (number1 == "1") {
      alert("2");
    }

That's why it's appearing twice. You can write the program as:

let number1 = parseInt(prompt("Input the first number"));
let op = prompt("Input operator")
let number2 = parseInt(prompt("Input 3rd number"));
if (op == ' ')
    alert(number1   number2);
else if (op == '-')
    alert(number1 - number2);
else if (op == '*')
    alert(number1 * number2);
else if (op == '/')
    alert(number1 / number2);
else
    alert("Please enter a valid operator");

Here we used parseInt(), that returns the first integer from a string.

  • Related