Jump to content

switch statement


a.c.

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');}

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...