简体   繁体   中英

If statement does not repeat when condition is met?

I want the script to keep prompting the user for a valid input which is from 0 to 100 but can't get it to work. I am more confused than when I started to work on this script last night. This is my homework and the teacher has asked us to use if statement that is why I haven't tried to use the while loop but maybe I should.

Here is the code.

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Grade</title> <script type="text/javascript"> var grade = Number(prompt("What did you score: ", "Your Score Here!")); if (grade < 0 || grade > 100) { grade = Number(prompt("Please enter a valid score", "Your Score Here!")); } else if (grade >= 0 && grade < 60) { grade = "F"; } else if (grade >= 60 && grade < 70) { grade = "D"; } else if (grade >= 70 && grade < 80) { grade = "C"; } else if (grade >= 80 && grade < 90) { grade = "B"; } else if (grade >= 90 && grade <= 100) { grade = "A"; } document.write("<strong>Your grade is:</strong> " + grade); </script> </head> <body> </body> </html> 

Yes you would use a while loop. In this case you would have a flag that checks if the input is invalid. We can assume it's valid in the loop, and when the invalid check goes through change it to being invalid (false), and cause the loop to repeat.

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Grade</title> <script type="text/javascript"> var grade = Number(prompt("What did you scrore: ", "Your Score Here!")); var valid = false; while(!valid) { valid = true; // assume it's valid if (grade < 0 || grade > 100) { grade = Number(prompt("Please enter a valid score", "Your Score Here!")); valid = false; // It it happens to not be valid, change it to invalid } else if (grade >= 0 && grade < 60) { grade = "F"; } else if (grade >= 60 && grade < 70) { grade = "D"; } else if (grade >= 70 && grade < 80) { grade = "C"; } else if (grade >= 80 && grade < 90) { grade = "B"; } else if (grade >= 90 && grade <= 100) { grade = "A"; } } document.write("<strong>Your grade is:</strong> " + grade); </script> </head> <body> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM