PDA

View Full Version : for loop problems

soaring206
12-19-2004, 10:00 AM
I'm trying to write a program that will allow users to order pizza online and enter the desired number of toppings for each pizza. I think I have the entire thing running correctly except that instead of adding the number of toppings for each pizza together to get a total number of toppings, it's just stringing them together. For example, if someone enters that they want 4 pizzas with 1, 3, 2, and 5 toppings, instead of returning a topping value of 11, it returns 5231. The function that contains this step is below...could someone please tell me where I'm going wrong and point me in the right direction? I didn't want to post too much code, but if you need more information, please reply and I can post as much of the code as you want to see. Thank you!

function toppings()
{var pizza1 = parseFloat(document.pizza_order.pizzas.value);
var message;
var x = 1;
var i;
var topping_no;
for(i=x; i<=pizza1; i++)
{message = "Please enter the desired number of toppings for pizza " + (x=i) + "";
topping_no = parseFloat(prompt(message, "0") + topping_no);}

Philip M
12-19-2004, 11:44 AM
Try

var i = 0;
var topping_no = 0;

to declare these variables as numbers, not strings.

soaring206
12-19-2004, 11:48 AM
Nope, that didn't work. Now it just adds a zero to the numbers of topping that it's stringing together. Thanks for the suggestion, though.

Philip M
12-19-2004, 12:21 PM
That shows that the variable is a string which is being concatenated.

Also try altering parseFloat to parseInt - presumably you can only have integer numbers of pizzas and toppings.

+ (x=i) Surely this is incorrect?

Brandoe85
12-19-2004, 12:36 PM
Try this:

<script language="javascript">
function toppings()
{var pizza1 = parseInt(document.pizza_order.pizzas.value);
var toppings = parseInt(topNum);
var message;
var i = 1;
var topping_no = 0;
for(i=1; i<=pizza1; i++)
{message = "Please enter the desired number of toppings for pizza " + i + "";
topping_no += parseInt(prompt(message, "0") + toppings);}
var topNum = topping_no;