Reputation: 31
I have let's say two answers one is string and another an integer trying to use switch with logical operators. Here is what I have and when I provide a number 1 it is not outputting related answer. Is there any way to accomplish that ?
How can accept an answer if it is given as a string or integer ?
I forgot to add this line of code
var test = prompt('your fav number ?');
user.toUpperCase();
switch(test) {
case 'one', 1:
var numberSentence = 'one';
var numbernumber = 1;
if(numberSentence === 'one' && numbernumber === 1) {
console.log('you got the answer') ;
}else {
console.log('pls try again');
}
break;
case 'two':
var twoSentence = 'two';
var twoNumber = 2;
if (twoSentence === 'two' || twoNumber === 2 ){
console.log('Cool you got it right');
}else {
console.log('do u want try again?');
}
console.log('it is two awesome' );
break;
case 'seven':
console.log('seven is my fav number as well ');
break;
default:
console.log('you could have at least said smth.');
}
Upvotes: 0
Views: 909
Reputation: 781984
You can't put two values in a single case
statement, but you can make use of fall-through. And if you're getting user input, it will always be a string, even if they type a number, so you should put it in quotes.
test = prompt("Please type a number");
switch (test) {
case "1":
case "one":
alert("That's the first number");
break;
case "2":
case "two":
alert("Second place isn't as good");
break;
case "3":
case "three":
alert("Three is a magic number");
break;
default:
alert("I don't know that number");
}
When a case
doesn't end with break
, it simply continues with the next case. This allows you to handle multiple cases with the same code.
Upvotes: 4