jeudi 24 septembre 2015

If/else statement within switch case

I'm new to js/programming and just making a simple calculator using prompt. I'm trying to validate that what's been entered are numbers and not strings. I tried this

var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();

switch (operatorType) {
    case 'add':
        var i = prompt("Enter your first number");
        var j = prompt("Enter your second number");
        if (isNaN(i) === false) && (isNaN(j) === false) {
            document.write(i+" plus "+j+" equals "+(i+j));
        } else {
            document.write("You didn't enter two numbers.");
        }
    break;

As well as if (i != 'string') && (j != 'string') but I keep getting "Unexpected token &&". I looked it up and if/else within a case is valid so I'm not sure what I'm doing wrong.

Full code if it helps

var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();

switch (operatorType) {
    case 'add':
        var i = prompt("Enter your first number");
        var j = prompt("Enter your second number");
        if (isNaN(i) === false) && (isNaN(j) === false) {
            document.write(i+" plus "+j+" equals "+(i+j));
        } else {
            document.write("You didn't enter two numbers.");
        }
    break;

    case 'subtract':
        var i = prompt("Enter your first number");
        var j = prompt("Enter your second number");
        document.write(i+" minus "+j+" equals "+(i-j));
    break;

    case 'multiply':
        var i = prompt("Enter your first number");
        var j = prompt("Enter your second number");
        document.write(i+" multiplied by "+j+" equals "+(i*j));
    break;

    case 'divide':
        var i = prompt("Enter your first number");
        var j = prompt("Enter your second number");
        document.write(i+" divided by "+j+" equals "+(i/j));
    break;

    default:
        document.write("Please enter whether you want to add, subtract, multiply or divide.");
    break;
}

Aucun commentaire:

Enregistrer un commentaire