# Javascript Esercise

## Recommended Posts

Hi, i am trying to solve this exercise:Write a script who asks numerical series. When the user inserts the keywords "end", it stops.If the user inserts an invalid value alert something.Confirm before to calculate the arithmetic mean.Print the result in a table.this is my code:

`		var stop="end";		num=prompt("Inserisci un numero","");		document.write(num);				var numero=isNaN(num);						while(num!=stop)		{		num=prompt("Inserisci un numero","");		document.write(num+ "<br>");							}				if (numero==true) {			alert("è possibile inserire solo interi");		}										}`

##### Share on other sites

well, you wold probably want your script to be constantly assigning a couple a counters relevant information. one counter to count the number of numbers put in, and another to be continuously adding each number the user puts in. With this information you can divide the sum of all the users numbers and then divide that by the amount of numbers given. Putting all this in an array could make it easier to then display back all the numbers in a table.

##### Share on other sites

well, you wold probably want your script to be constantly assigning a couple a counters relevant information. one counter to count the number of numbers put in, and another to be continuously adding each number the user puts in. With this information you can divide the sum of all the users numbers and then divide that by the amount of numbers given. Putting all this in an array could make it easier to then display back all the numbers in a table.
I created the counter to count the number of numbers, but how could is it possible a counter to sum the numbers of the prompt?Beacause how can i sum something who doesn't exist yet. my script now is:
`var cont0=1;		var stop="end"		   		var num=prompt("inserisci un numero","");		var number=isNaN(num);				if (number==true && num!=stop) {			alert("inserire solo valori numerici interi");		}		   		while (num != stop) {	   			num=prompt("inserisci un numero","");	   			cont0++;		 	}									alert("finalmente hai inserito end!");			  alert("hai inserito " + contatore + " numeri");`

##### Share on other sites

Using isNaN alone isn't enough. First you should check if the value is the stop value, and if it's not then you should use parseInt to convert the value to an integer. Then you can use isNaN with the return value from parseInt, that will tell you if they entered something invalid. Once you convert the value to a number using parseInt you can also add it to your total variable to keep track of the sum.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account