Jump to content

switch statement


a.c.
 Share

Recommended Posts

Hi i'm new at this and i was trying something out but can't understand why its not working. I'm trying to create a prompt where the user enters a number. If the number is "10" then it is correct. If the answer is higher then "10" should say "too high". If answer is lower than "10" should say "too low". below is the code that I have written. var enT= prompt("enter a number");var numB= "10";var boTH=enT == numB;switch(boTH){case 1: document.write("number is too high"); break;case 2: document.write("correct"); break;default: document.write("number is too low");}

Link to comment
Share on other sites

Hi i'm new at this and i was trying something out but can't understand why its not working. I'm trying to create a prompt where the user enters a number. If the number is "10" then it is correct. If the answer is higher then "10" should say "too high". If answer is lower than "10" should say "too low". below is the code that I have written. var enT= prompt("enter a number");var numB= "10";var boTH=enT == numB;switch(boTH){case 1: document.write("number is too high"); break;case 2: document.write("correct"); break;default: document.write("number is too low");}
first off, I'm not quite sure what this line is
var boTH=enT == numB;

also, the cases have to be what you're actually testing for, not just arbitrary counting of numbers. also, you may want to consider making your variable names more meaningful.

var userInput = prompt("enter a number");var targetNumber = 10;switch(parseInt(userInput)){  case userInput === targetNumber:	document.write("correct");	break;  case userInput > targetNumber:  	document.write("number is too high");	break;  case userInput < targetNumber	document.write("number is too low");	break;  default	document.write('I dont understand what you entered.  Please try again');}

Edited by thescientist
Link to comment
Share on other sites

The switch condition in that case should just be "true" (find the case that is true), and it might be better to catch the error first:

var userInput = parseInt(prompt("enter a number"), 10);var targetNumber = 10;switch(true){  case isNaN(userInput):	document.write('You did not enter a number');	break;  case userInput === targetNumber:	document.write("correct");	break;  case userInput > targetNumber:  	document.write("number is too high");	break;  case userInput < targetNumber:	document.write("number is too low");	break;}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...