While loop - number counter minus 0

0

Good evening!

I need to apply a loop for the user to always enter a number (via prompt), when typing 0 should appear an alert stating the number of numbers entered, not counting zero.

I'm not understanding what I'm doing wrong, as it is displaying an alert with all the numbers entered, including zero.

Does anyone know how I can do to count only the number of numbers excluding zero?

Thank you.

function TESTE2() {

        var number = prompt("Enter a number, 0 to stop: ");
        var result = 0;

        while (number !== 0){
            result = result+number;
            number = +prompt("Enter another, chose 0 to stop");
            }

        while (number == 0){
            alert("You entered "+ result+ " non-zero numbers!");
            break;
            }           
    }
    
asked by anonymous 28.01.2017 / 06:45

3 answers

1

You can use array , make push whenever the value is not 0 and, at the end, return length of array :

var numbers = [];

function loopPrompt() {
  var input = prompt('Number? [0 escapes]');

  if (!input || parseInt(input,10) === 0) {
    alert(numbers.length + ' numbers were inserted: ' + numbers.toString());
    return;
  }

  numbers.push(input);
  loopPrompt();
}

loopPrompt();
    
28.01.2017 / 15:34
1

I believe that in the example of hpedrorodrigues solves your problem however changing! == by! = the reason I mentioned before

(function () {
    var number = prompt("Enter a number, 0 to stop: ");
    var quantity = 0;

    while (number != 0) {
        quantity++;
        number = Number(prompt("Enter another, chose 0 to stop"));
    }

    alert("You entered " + quantity + " non-zero numbers!");
}());
    
28.01.2017 / 15:46
1

Just do this:

(function () {
    var number = prompt("Enter a number, 0 to stop: ");
    var quantity = 0;

    while (number != 0) {
        quantity++;
        number = Number(prompt("Enter another, chose 0 to stop"));
    }

    alert("You entered " + quantity + " non-zero numbers!");
}());

I hope I have helped!

    
28.01.2017 / 13:37