This is a discussion on "Problem with a switch case" within the JavaScript Forum section. This forum, and the thread "Problem with a switch case are both part of the Program Your Website category.
|
|
|
|
|
![]() |
||
Problem with a switch case
|
||
| Notices |
![]() |
|
|
LinkBack | Thread Tools |
|
|||
|
Problem with a switch case
Hi Everyone,
I need some help with a switch case. No matter what I do, it keeps giving me the default answer for no. Here is the code... <html> <head> <title>Project 3</title> <script type = "text/javascript"> <!-- var value1, value2, answer, studentanswer, figure, choice; value1 = Math.floor( 1 + Math.random() * 9 ); value2 = Math.floor( 1 + Math.random() * 9 ); document.writeln( "How much is " + value1 + " times " + value2 + "? "); //gets number from text field on form function getAnswer() { var studentanswer = parseFloat (document.myform.studentanswer.value); answer = value1 * value2; figure = calculation (studentanswer); } //defines the function called calculation function calculation (studentanswer) { if (studentanswer == answer) { choice = (Math.random() *5); switch (choice) { case 0: window.status = "Very Good!"; break; case 1: window.status = "Excellent!"; break; case 2: window.status = "Nice Work!"; break; case 3: window.status = "Keep up the good work!"; break; default: window.status = "Yes, Something is not right"; } } else window.status = "No, please try again."; choice = (Math.random() *5); switch (choice) { case 0: window.status = "No, please try again"; break; case 1: window.status = "Wrong. Try once more"; break; case 2: window.status = "Don't give up!"; break; case 3: window.status = "No, keep trying"; break; default: window.status = "No, Something is not right"; } } // --> </script> </head> <body> <form name = "myform" action = ""> Enter the answer here <input name = "studentanswer" type = "text" /> <input type = "button" value = "Calculate" onclick = "getAnswer()" /> </form> </body> </html> Any help would be greatly appreciated! Thanks! Jennifer |
|
|
|
|||
|
choice = (Math.random() *5);
This won't give you integers, which is what you're testing for in your switch - it gives you things like 1.2357972257 You need to round it, like you did in this line value1 = Math.floor( 1 + Math.random() * 9 ); |
|
|||
|
Quote:
http://www.w3schools.com/js/js_switch.asp |
![]() |
| Tags |
| problem, switch, case |
| Thread Tools | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| [SOLVED] Switch(score) | warren1978 | JavaScript Forum | 3 | Mar 24th, 2008 07:09 |
| case : 'example' help | jahphill | PHP Forum | 4 | Nov 29th, 2007 19:43 |
| Switch to linux? | alexgeek | Webforumz Cafe | 7 | Oct 10th, 2007 21:00 |
| switch post | alexgeek | PHP Forum | 12 | Sep 25th, 2007 10:04 |
| CSS style switch | Heavensword | Web Page Design | 3 | Jul 24th, 2007 15:24 |