Reputation: 11
I am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
- Creates a variable 'total' with a value of 0.
- Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
- If the user enters a number, add the new number to a running total.
- If the user enters the word "quit" the loop should stop execution.
- If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
- When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping. Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
Upvotes: 0
Views: 208
Reputation: 26
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".
Upvotes: 1