1

I need to prompt the user to enter a series of numbers, or the word "quit". Then, If the user enters a number, add the new number to a running total. And, If the user enters the word "quit" the loop should stop execution. I cant figure what should I do here. Im a beginner. i don't know how to make it work when user enter a word quit

let total = 0;
let number = 0;
do {
 total += number;
 number = parseInt(prompt('Enter a number: '));
 if (number >= 0) {
 document.writeln("<p>You entered " + number + "!</p>");
 } else {
 if (isNaN(number)) {
 number = parseInt(prompt('Enter a number: '));
 document.writeln("<p>Try again. We are looking for a number!</p>");
 }
 }
} while (number >= 0)
document.writeln("<p>The total is " + total + "</p>")

Rickard Elimää
7,6963 gold badges18 silver badges36 bronze badges
asked Mar 13, 2022 at 21:53
1
  • Just a heads up. The loop breaks if you enter a letter two times in a row. Commented Mar 14, 2022 at 1:31

1 Answer 1

1

Use break to stop the javascript loop:

let total = 0;
let number = 0;
 do {
 total += number;
 text = prompt('Enter a number: ');
 if (text == "quit") {
 break;
 }
 number = parseInt(text);
 if (number >= 0) {
 document.writeln("<p>You entered " + number + "!</p>");
 } else {
 if (isNaN(number)) {
 number = parseInt(prompt('Enter a number: '));
 document.writeln("<p>Try again. We are looking for a number!</p>");
 } 
 }
 } while(number >= 0)
 document.writeln("<p>The total is " + total + "</p>")
answered Mar 13, 2022 at 21:58
Sign up to request clarification or add additional context in comments.

2 Comments

wow..thank u sir.. it works.. i appreciate it a lot
No problem! Can you please mark the answer as solved? Thx!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.