The Else is not recognized

Asked

Viewed 116 times

-2

Estou aprendendo JS

   alert("");
            var n1=parseInt(prompt("Digite um número"));
            var n2=parseInt(prompt("Digite outro número"));
            var A = n1+n2;
            var M = n1*n2;
            var D = n1/n2;
            var Sub = n1-n2;

            var menu=prompt("Escolha uma opção:\nA - Adição\nM - Multiplicação\nD - Divisão \nS - Subtração")

            if(menu == A);{
                alert(A);
            }else(menu == M);{
                alert(M);
            }

2 answers

3

The ideal would be to learn in a structured way, to understand the why of each thing.

Can’t have a semicolon after the condition of if or else. The ; contains a statement, and the entire block of the if is a unique statement.

Besides, when you’re gonna put a condition on else must be followed by a if.

By Fima when you compare a variable with a text, the text must be in quotes, otherwise it is interpreted as variable.

There are a number of other things that can be improved in this code.

var n1 = parseInt(prompt("Digite um número"));
var n2 = parseInt(prompt("Digite outro número"));
var A = n1 + n2;
var M = n1 * n2;
var D = n1 / n2;
var Sub = n1 - n2;
var menu = prompt("Escolha uma opção:\nA - Adição\nM - Multiplicação\nD - Divisão \nS - Subtração")
if (menu == "A") {
    alert(A);
} else if (menu == "M") {
    alert(M);
}

I put in the Github for future reference.

1


There are some problems in your code:

  1. There’s no semicolon (;) after if and else;
  2. How are you trying to compare with the value of prompt typed by the user, the letter A would be a String, so it should be placed between quotes, otherwise javascript will look for a variable with the name A, unlike the letter A itself.
  3. In the case of else there is a condition within. Think about the else as but all other options. If you want to put a condition, could use the else if, but in your case it is not necessary.

Below your example working very simple your menu, with if, else if and else, foreseeing all their cases.

var n1 = parseInt(prompt("Digite um número"));
var n2 = parseInt(prompt("Digite outro número"));
var A = n1 + n2;
var M = n1 * n2;
var D = n1 / n2;
var Sub = n1 - n2;

var menu=prompt("Escolha uma opção:\nA - Adição\nM - Multiplicação\nD - Divisão \nS - Subtração")

if (menu === 'A') {
  alert(A);
} else if (menu === 'M') {
  alert(M);
} else if (menu === 'D') {
  alert(D);
} else {
  alert(Sub);
}

  • Thanks Maniero, you’ve helped so much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.