[英]If/else statement within switch case
I'm new to js/programming and just making a simple calculator using prompt. 我是js /编程新手,只是使用提示制作一个简单的计算器。 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 &&". 和
if (i != 'string') && (j != 'string')
但我不断收到“意外令牌&&”。 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;
}
You have your parenthesis in the wrong spot causing the syntax error. 您的括号位置错误,导致语法错误。 You need to move the parenthesis in this line to change from:
您需要在此行中移动括号才能更改为:
if (isNaN(i) === false) && (isNaN(j) === false) {
So that it becomes: 这样就变成:
if (isNaN(i) === false && (isNaN(j) === false)) {
You'll also need to convert the strings to numbers so that your code truly adds/etc instead of concatenates the text. 您还需要将字符串转换为数字,以便您的代码真正添加/等,而不是串联文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.