0
I make a Calculator in JavaScript
I make a Calculator in Java script but the code dosnt going: var y = 30 var x = 10 var resu = 2 var op = prompt("Schreibe den Operator"); if (op = "+") { resu = (x + y); alert("Das ergebnis ist:" + resu); } else { if (op = "-") { resu = (y - x); alert("Das ergebnis ist: " + resu); } } else { if (op = ""){ alert("Sie haben keinen gültigen Operator angegeben"); } }
8 Respuestas
+ 9
if (op == "+") ……
+ 9
var y = 30;
var x = 10;
var resu = 2;
var op = prompt("Schreibe den Operator");
if (op == "+") {
resu = (x + y);
alert("Das ergebnis ist:" + resu);
} else {
if (op == "-") {
resu = (y - x);
alert("Das ergebnis ist: " + resu);
}
} else {
if (op == ""){
alert("Sie haben keinen gültigen Operator angegeben");
}
}
+ 7
works?
+ 6
Complement to @ValentinHacker:
Replace the single equal sign by a paired one (==): one equal sign is the affectation operator, since two are comparison operator ^^
+ 4
@Finnlukas:
Why don't you answer to @Filip?...
Well, for your pleasure, your code corrected, so it's work:
var y = 30;
var x = 10;
var resu = 2;
var op = prompt("Schreibe den Operator");
if (op == "+") {
resu = (x + y);
alert("Das ergebnis ist:" + resu);
}
else if (op == "-") {
resu = (y - x);
alert("Das ergebnis ist: " + resu);
}
else if (op == "") {
alert("Sie haben keinen gültigen Operator angegeben");
}
I've just removed ( and reformat a little ) the brackets of your 'else' statement... If you enclose the 'if' statement, the next ( second ) else statement will attempt to be linked to the first, instead of the second 'if':
if (false) {
/* code not executed */
}
else { /* block executed */
if (false) {
/* code not executed */
}
}
else {
/* what else? this is the error displayed by javascript interpretor */
}
So, if you don't remove the brackets ( if the 'else' block contains more than one instruction -- 'if' and its block is once instruction ), you need to close the first 'else' block after the second, which applied to the second if:
if (false) {
/* code not executed */
}
else { /* block executed */
if (false) {
/* code not executed */
}
else {
/* what else? this is the error displayed by javascript interpretor */
}
}
Notice the indentation changes: this help greatly to see mistake ;)
[ EDIT ]
@Kamil is right ^^
( but it was working without for me, in code playground, on app' / tablet android Oo )
+ 3
Thanks for the Code
+ 3
don't forget the semi colons in the first 3 lines
+ 2
Thanks for good anwser