What is wrong with my code?? Everything except the subtraction works. It just returns NaN. I am new to javascript so i might have written my code poorly.
// Variables
var count = prompt("Choose an arithmetic method: \n1. Addition \n2. Subtraktion\n3. Multiplikation\n4. Division");
var x = parseInt(prompt("Enter your first number", "0"));
var y = parseInt(prompt("Enter your second number", "0"));
var z = +x + +y;
// Switch function with 4 cases
switch(count) {
case '1':
alert("Answer: " + z);
break;
case '2':
alert("Answer: " + x - y);
break;
case '3':
alert("Answer: " + x * y);
break;
case '4':
alert("Answer: " + x / y);
break;
}
You need to group the operations in parentheses, for instance alert("Answer: " + (x - y));
(and the same for the others). Otherwise JavaScript runs "Answer: " + x
first, resulting in a string.
Also, always specify the radix (you want 10) for parseInt: parseInt(input, 10)
, otherwise some engines get confused with octal numbers.