Here's the problem I'm trying to solve: Write a program that asks a user to enters pairs of numbers until they enter "quit". As each pair of numbers is entered and validated, add the numbers using a function. The function will have two parameters for the pair of numbers and will return the sum. After the user enters "quit", output all the pairs of numbers and their sums.
I've got the program to output number1, number2 and the sum when I just do one, but when I try to repeat until the user enters "quit" I seem to break it?
//function to sum 2 entered numbers
function sum2enteredNumbers(number1, number2)
{
var sum1and2;
sum1and2 = number1 + number2;
return sum1and2;
}
function exercise4Part1() {
// PART 1: YOUR CODE STARTS AFTER THIS LINE
var QUIT_CODE = "quit";
var output;
var number1;
var number2;
while (number1 !== QUIT_CODE || number2 !== QUIT_CODE)
{
number1 = Number(prompt("Enter a number:"));
number2 = Number(prompt("Enter another number:"));
}
sum1and2 = sum2enteredNumbers(number1, number2);
output = document.getElementById('outputPart1');
output.innerHTML = "<br />Entry 1: " + number1 + " Entry 2: " + number2 + " Sum: " + sum1and2;
}
Attempt 2--still not working:
function sum2enteredNumbers(number1, number2)
{
var sum1and2;
sum1and2 = number1 + number2;
return sum1and2;
}
function exercise4Part1() {
// PART 1: YOUR CODE STARTS AFTER THIS LINE
var QUIT_CODE = "quit";
var output;
var number1;
var number2;
while (number1 !== QUIT_CODE && number2 !== QUIT_CODE)
{
number1 = prompt("Enter a number or \"quit\":");
number2 = prompt("Enter another number or \"quit\":");
if (number1 !== QUIT_CODE && number2 !== QUIT_CODE)
{
number1 = Number(number1);
number2 = Number(number2);
}
}
sum1and2 = sum2enteredNumbers(number1, number2);
output = document.getElementById('outputPart1');
output.innerHTML = "<br /> Entry 1: " + number1 + " Entry 2: " + number2 + " Sum: " + sum1and2;
}
Conceptually, you want to do this:
For step 1, you're most of the way there. Consider this function:
function getInput(msg) {
var value = prompt(msg);
if (value === QUIT_CODE) {
return false;
}
return value;
}
You can then call this function in the while
condition, while still assigning the input to number1
or number2
.
while ((number1 = getInput('Enter a number')) &&
(number2 = getInput('Enter another number'))) {
// convert and output
}
Why does this work?
&&
, ||
, i.e. JavaScript's logical boolean operators short circuit, which means the condition will be false
without evaluating the second operand if the first operand is false for &&
, and the condition will be true
without evaluating the second operand if the first operand is true
.0
as falsey in JavaScript which would cause the while condition to fail and not work if the user entered 0. However in this case, the source of the input is a string, and the expression '0'
is truthy.