javascriptfunctionloopssentinel

user to enters pairs of numbers until they enter "quit", sentinel not working?


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;

}

Solution

  • Conceptually, you want to do this:

    1. Get the user input,
      • if at any time the input is "quit", then stop. (the sentinel check)
    2. perform the addition operation,
    3. output,
    4. repeat.

    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?