1 (9 pts.). You are provided at the assignment site the HTML document prob1.html
ID: 3600169 • Letter: 1
Question
1 (9 pts.). You are provided at the assignment site the HTML document prob1.html, which references the JavaScript file prob1.js (which you write) and calls function go() when the body finishes loading. File prob1.js contains only the definition of go().
The body of function go() consists of a while (true) loop. Each iteration prompts for a positive number x to add to the sum it is accumulating. The user exits the loop by clicking Cancel (or striking the Esc key). The body of the while loop is a try-catch statement. In the try block, the user provides the value for x. If the user clicked Cancel, we break out of the loop. If the value provided (always a string) cannot be converted to a number, we throw an expression to the effect that the value is not a number (and ask the user to try again). If the value provided is a number but is not positive, we throw an expression to the effect that the value is not positive. And, if the value does convert to a positive number, we convert it and add it to the running sum. The catch block consists of a single statement, which raises an alert box whose content is the exception value.
The following is a sequence of screenshots where we enter ‘2’, then ‘a’ (flagged as not a number), then ‘3’, and then ‘0’ (flagged as not positive). We then click Cancel when prompted for another number, and an alert box appears with the sum 5.
The following is part of the definition of function go(). Only the first statement in the try block is shown, and the statement making up the catch block has been removed. You can download a file with this partial code from the assignment site. Fill in the missing code as described above.
function go() {
var x, sum=0.0;
while (true) {
try {
x = window.prompt( "Enter a positive number. Cancel to exit.", 1 );
}
catch (e) {
}
}
window.alert( "The sum is " + sum );
}
Explanation / Answer
function go() {
var x, sum = 0.0;
while (true) {
try {
//get user input
x = window.prompt("Enter a positive number. Cancel to exit.", 1);
//break loop on cancel
if (x == null) {
break;
}
//check if x is string
if (isNaN(x)) {
throw "Not a Number. Try again";
}
//convert x to number
x = Number(x);
//throw error if x<0
if (x < 1) {
throw "Number is not positive ."
} else {
sum = sum + x;
}
}
//alert error message
catch (e) {
window.alert(e);
}
}
//alert sum
window.alert("The sum is " + sum);
}
//call function
go();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.