what to put in javascript to know that i input a number? - javascript

so i just learned javascript, and learning switch, so i want to know how if i input any number, the alert can know its a number, and the else is anything that not number
var thisVarA = +prompt('a?', '');
switch (thisVarA) {
case 1:
alert('you input number 1');
break
case 2:
alert('you input number 2');
break
case 3:
alert('you input number 3');
break
case 4:
alert('ok this is more than enough');
break
default:
alert('its not just a number');
}
so i want case 4 is if i put any number other than 1,2,3 the alert can know it and put ok its a number
and the else is anything than number even if its has a number ike milano1010

Instead of a switch statement, this would be better for just an if statement.
if (!isNaN(thisVarA)) {
alert('you input number ', thisVarA);
} else {
alert('its not a number');
}
Here we do several things. isNaN checks if it is not a number. We use ! before it to reverse that logic so now we check if it IS a number. The alert starts with 'you input number ' and fills in the number automatically with your variable number instead of needing to check each case. Else is anything that is not just a number like milano1010

Based on your requirements: (switch + determining whether the input is numeric):
<script>
var thisVarA = +prompt('a?', '');
switch (true) {
case thisVarA==1:
alert('you input number 1');
break
case thisVarA==2:
alert('you input number 2');
break
case thisVarA==3:
alert('you input number 3');
break
case Number.isNaN(thisVarA)==false:
alert('ok its a number');
break
default:
alert('it is anything than number');
}
</script>
The Number.isNaN() function determines whether a value is an illegal number (Not-a-Number)

There is a slight sublety in your set up as there is a + immediately in front of your prompt. Javascript takes this to be an arithmetic operation in this situation and therefore forces whatever you input to be of type 'number'. If it were not there the result of your prompt would not be forced to be of type number.
As it is, when you type something like abc123 it is forced to be a number, but it isn't one. Javascript in this situation will give it type 'number' but its value will be NaN (not a number).
Here's your switch with an alert to show you the type and under the default we check whether it's NaN or not.
var thisVarA = +prompt('a?', '');
alert('The type is ' + typeof(thisVarA));
switch (thisVarA) {
case 1:
alert('you input number 1');
break
case 2:
alert('you input number 2');
break
case 3:
alert('you input number 3');
break
default:
if (!isNaN(thisVarA)) {
alert('you input number ' + thisVarA);
}
else {
alert('its not just a number');
}
}

Related

How to make "case 3" into some sort of "case random"

I'm completing something for an assignment in my coding course, but I am stuck on a part of trying to set a number to random. Also, there are 3 blocks that have this, except the last block does not have an event.stopPropagation();.
I have tried setting "case 3" (which needs to be edited to something else) to "case random" but that did not work. It would only make it so that anything you would type in the prompt() would display the "You got it!" message.
...
alert( "Guess the number I'm thinking. It's between 1 and 5. You have 3 tries." )
var min = 1;
var max = 5;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
prompt( "You have 3 tries remaning." );
switch ( random )
{
case 3: alert( "You got it!");
event.stopPropagation();
break;
default: alert( "That is incorrect. Try again." );
break;
}
...
I expect it to set a random (whole) number and have the user able to guess it, and have it validate properly.
Also, if there is anything else wrong with this block of code, could you please help me?
You need to get the user's input - the prompt is an orphaned expression.
var guess = +prompt(...);
Then switch on the guess:
switch(guess) {
case random:
alert("You got it!");
event.stopPropagation();
break;
default:
alert("That is incorrect. Try again");
break;
}
Switching isn't the best practice here however - as Barmar points out, an if is better and easier:
if (guess == random) {
alert("You got it!");
event.stopPropagation();
} else {
alert("That is incorrect. Try again");
}

Switch statement compare user input Javascript

I'm trying this simple code and seems like the user's input is not going through all the comparisons and jumps to the default one right away. I'm guessing that JS is taking the user's input as a string instead. I did try to parseInt() but didn't work. Here is my code;
var number = prompt('What\'s your favority number?');
switch(number){
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
Use true as an expression for switch.
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.[Ref]
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) . If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
switch (true) {
//----^^^^
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Edit: As suggested by #bergi in the comments, an if/else cascade is the best approach for this problem.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
if (number < 10)
console.log('Your number is to small.');
else if (number < 100)
console.log('At least you\'re in the double digits.');
else if (number < 1000)
console.log('Looks like you\'re in three digits.');
else
console.log('Looks like you\'re in the fouth digits.');
You're not understanding how the switch statement works. It is not a shortcut for checking dynamic values. It's a shortcut for checking known values.
Each case is a statement that gets evaluated to a value. If you look at the docs, you'll see that they have case: value, rather than what you are attempting, which is case: (expression). So, it's going to turn all your expressions into values.
So, for example, your first case is:
case (number < 10):
But what that really becomes is:
case false:
And of course, no number will evaluate to false (technically 0 is a falsey value, but the switch uses === comparison rather than == so 0 === false // false). Thus, all your cases are really case false, and so the switch is falling through all of them and landing on the default case.
So, for your situation, the switch statement is inappropriate. You should use if statements.
if(number < 10) {
} else if(number < 100) {
} else if(number < 1000) {
} else {
}
The switch statement is only appropriate when you know the values:
switch(number) {
case 10:
break;
case 100:
break;
case 1000:
break;
default:
}
(And yes, use parseInt to ensure you have integers.)

If else returning true value, when the value is actually false

I am making a program that asks the user for 2 numbers ( a and b). Then the program asks them if they want to add, subtract, multiply, or divide, by inputting the number 1 for addition, 2 for subtract, 3 for multiply, and 4 for division. If any other number other than 1-4 is inputted ( say 0) the program must stop, and an alert tells them to re try the calculation. if the user inputted the first 3 numbers correctly, then they should get their computation in an alert box (THIS IS NOT WORKING!).
Then they are asked with a prompt box if they wish to do another computation ( y to continue, anything else ends the program), the prompt shows, but if i input anything the program continues. there is an If else statement within the cont1() function which is called when the user inputs a number corresponding to the arithmetic he/she wishes to complete.
Currently I have no console errors, my first 3 prompt boxes from my getValues() function works properly, but the arithmetic of the add(), subtract, etc functions are not working properly, the alert window never pops up with the answer.
HERE IS MY CODE!(EDITED 3/10/16 10:31)
EDIT: MY if else statement is working now.. But the arithmetic is still not working.
10:31 EDIT: The arithmetic portion is now fixed because i didn't have the parseInt(), but the cont1() function is still executing as true when the input by the user is suppose to stop the prorgam
10:52 edit : With the getValues() function : the function checks to see if a, b and c are numbers, when i input all numbers it returns that they are not numbers. Also got rid of the arithmetic functions, converted them over to a switch statement.
<!DOCTYPE html>
<html lang="en-US">
<title> B_Math Calculator </title>
<head>
<script>
function getValues()
{
var a = parseInt(prompt("please enter the first number"), 1);
var b = parseInt(prompt("please enter the second number"), 2);
var c = parseInt(prompt("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE"), 1);
if(isNaN(a) || isNaN(b) || isNaN(c)){
alert("One or more of your inputs were not numeric!");
}
alert("Answer is: " + calc(a,b,c));
cont1();
}
function calc(oper1, oper2, oper3){
switch (oper3){
case 1:
return oper1 + oper2;
break;
case 2:
return oper1 - oper2;
break;
case 3:
return oper1 * oper2;
break;
case 4:
return oper1 / oper2;
break;
default:
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
break;
}
}
// ASK IF USER IS DONE (Y FOR YES , ANYTHING ELSE FOR NO)
function cont1()
{
var answ = prompt("Next computation? Y : yes, any other letter for no.");
if(answ.toLowerCase() === "y") {
getValues();
} else {
alert("thank you for using my calculator!");
}
}
</script>
</head>
<body>
<button onclick="getValues()" value="Call Function"> Click here to do some math! </button>
</body>
</html>
This is the correct way to accomplish what you want:
if(c==1) {
add(a,b);
} else if(c==2) {
subtract(a,b);
} else if(c==3) {
multiply(a,b);
} else if(c==4) {
divide(a,b);
} else {
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
}
Or, better yet:
switch (c){
case 1:
add(a,b);
break;
case 2:
subtract(a,b);
break;
case 3:
multiply(a,b);
break;
case 4:
divide(a,b);
break;
default:
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
break;
}
Which is a much cleaner way to structure an if/else that only takes a single expression into account.
In either case, proper indentation makes the code much more readable.
You also have problems with the location of your return statements in that you have more code that comes after them. A return statement doesn't just return a value to the caller, but it also returns programmatic control to the caller, meaning that your function ENDS when it encounters return. So, in your case, no code that comes after the return will be processed.
Additionally, in your cont1() function, your test is:
if(answ = "y")
This is not testing answ to see if it has a value of "y", the single equal sign is assigning the value of "y" to answ, which is an operation that evaluates to true, meaning that you will always execute the code in the true branch. You need to use double (==) or triple (=== for equality without conversion) to compare values.
As I've mentioned, proper code formatting is important, not only for readability, but for processing. Opening curly braces should appear at the end of the line for which they belong. This:
function foo()
{
and this:
if(condition)
{
true code
}
else if (condition)
{
Should be:
function foo() {
and this:
if(condition) {
true code
} else if (condition) {
As a side note, your code assumes that the user input will be numeric, which is wrong for two reasons.
A prompt ALWAYS returns a string, regardless of the input.
The user might (will) type something unexpected, like "one"
Before operating on the input, you should check it. There are many techniques for determining if input is numeric (many have pros and cons), but something along the lines of the following would be appropriate:
var a = parseInt(prompt("please enter the first number"),10);
var b = parseInt(prompt("please enter the second number"),10);
var c = parseInt(prompt("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE"),10);
if(isNaN(a) || isNaN(b) || isNaN(c)){
alert("One or more of your inputs were not numeric!");
}
Lastly, instead of having 4 separate functions that largely do the same thing and decide which one to call with an if or switch, why not just have one function that decides what math to do based on an input parameter.
See this fiddle for a complete solution that incorporates all these points, using switch: https://jsfiddle.net/m0r5r4dx/17/
(c!=1,2,3,4)
The comma operator returns whatever is on the right hand side, so this evaluates as:
(false,2,3,4)
which evaluates as:
4
Use an array if you want to tell if a value isn't in a set.
if ( -1 == [1, 2, 3, 4].indexOf(c) )
else if (c!=1,2,3,4)
This isn't doing what you think it's doing. What this is doing is:
Checking if c isn't equal to 1.
Checking if 2 is truthy (which it is).
Checking if 3 is truthy (which it is).
Checking if 4 is truthy (which it is).
Due to the commas, the value returned is actually 4 (meaning the if statement ignores the first 3 anyway).
What you need to do is change this else clause to:
if (c != 1 && c != 2 && c != 3 && c != 4)
Or:
if (c < 1 || c > 4)
I suggest you take a look at MDN's notes on if...else before doing anything else.
As other answers have mentioned, your method of checking if c is 1, 2, 3, or 4 is incorrect, but you don't actually need your last else if to be an else if, as by the time you've reached it you already know that c is not 1, 2, 3, or 4. You could replace it with an else, and it should work.
Also, your various functions have code after the return that will never execute, as the function finishes as soon as it reaches a return. Since you aren't actually doing anything with the value you return, you should probably remove the return statements.

Compare strings without being case-sensitive

I have problem with a variable I made (it's a string) in JavaScript. It will be prompt from the user and then with the switch I will check if it is true or not. Then when I input it upper case it will say it is identified as a another var.
Here is my code:
var grade = prompt("Please enter your class") ;
switch ( grade ){
case "firstclass" :
alert("It's 500 $")
break;
case "economic" :
alert("It's 250 $")
break;
default:
alert("Sorry we dont have it right now");
}
Just lower case it initially.
var grade = prompt("Please enter your class").toLowerCase() ;
as #nicael stated just lowercase what they input. However, if you need to preserve the way it was input and only compare using the lowercase equivalent, use this:
var grade = prompt("Please enter your class") ;
switch ( grade.toLowerCase() ){
case "firstclass" :
alert("It's $500");
break;
case "economic" :
alert("It's $250");
break;
default :
alert("Sorry we don't have it right now");
}
You could set the entire string to lower case by using the String prototype method toLowerCase() and compare the two that way.
To keep the input the same, mutate the string during your switch statement:
switch( grade.toLowerCase() ) {
// your logic here
}
You should always compare uppercase string with uppercase values in case sensitive languages.
Or lower with lower.
var grade = prompt("Please enter your class") ;
switch (grade.toUpperCase())
{
case "FIRSTCLASS" :
alert("It's 500 $")
break;
case "ECONOMIC" :
alert("It's 250 $")
break ;
default :
alert("Sorry we dont have it right now");
}

Switch Test if isNan

In a switch statement, I want make sure the user did not type a number. I get an error with this:
"case !isNaN(user):"
var user = prompt("Hey! What do you like?","").toLowerCase();
switch(user){
case "":
console.log("Can\'t be blank!");
break;
case !isNaN(user):
console.log("Can\'t be a number");
break;
case "food":
console.log("Food does a body good...sometimes");
break;
default:
console.log("Mmm....Can\'t Make heads or tales of this one.");
}
I tried this too, but not working:
switch(!isNaN(user)){
case true:
console.log("Hey! Can\'t be a number!");
break;
I can get !isNaN to work in an else if, but not in a switch.
var user = prompt("Hey! What do you like?","").toLowerCase();
if(!isNaN(user)){
console.log("Can\'t be a Number!");
}
The switch statement is comparing your user variable to each case. so it has to be read like
does user == "". Yes? do stuff
does user == "food". Yes? do stuff
otherwise, do stuff
when you read a case statement like this, you'll realise why your NaN case doesn't work
does user == isNaN(user) <- will never be true
Your final code is the way you need to do it
var user = prompt("Hey! What do you like?","").toLowerCase();
if(!isNaN(user)){
console.log("Can\'t be a Number!");
}

Categories