for loop - undefined error - please help

wxdqz

New Member
I'm having a truly horrible day :( This is telling me that totalMpg is undefined... It was working just fine until I changed my while loop into a for loop... Can someone please help me with this???

Thank you :)

var milesDriven, // miles driven per tank - entered by user
gallonsUsed, // gallons used per tank - entered by user
mpg, // miles per gallon
tankCounter // tank - counter
//tanks, // number of tanks - entered by user
totalMpg, // total miles per gallon - accumulator
mdValue, // miles driven value
guValue, // gallons used value
tankValue,


totalMpg = 0; // set accumulator to zero
tankCounter = 0; // set counter to zero

//read in number of tanks from user as a string
tankCounter = window.prompt("Enter the number of tanks, -1 to Quit:", "0");

// read in first number from user as a string
milesDriven = window.prompt("Enter miles, -1 to Quit:", "0");

// convert numbers from strings to integers
mdValue = parseInt(milesDriven);
tankValue = parseInt(tankCounter);

// write heading and create table
document.writeln("<H1>Miles Per Gallon</H1>");
document.writeln("<TABLE BORDER = '1' WIDTH = '75%'>");

// go through this loop until the user enters -1
for (var tankCounter = 1; tankCounter <= tankValue; tankCounter++)
tankValue += tankCounter;
{

// read in second number from user as a string
gallonsUsed = window.prompt("Enter gallons used, -1 to Quit:", "0");

// convert numbers from strings to integers
guValue = parseInt(gallonsUsed);

tankCounter = tankCounter + 1; // keep a count of how many tanks

mpg = mdValue / guValue; // divide miles driven by gas used to get miles per gallon

document.writeln("<TR><TD><H3>Tank " + tankCounter + ": </H3>" + mpg + " mpg.</TD></TR>");

totalMpg = totalMpg + mpg; // accumulate total miles per gallon

// read in first number from user as a string
milesDriven = window.prompt("Enter miles, -1 to Quit:", "0");

// convert numbers from strings to integers
mdValue = parseInt(milesDriven);
}

// do this after the user enters -1
if (tankCounter != 0) // check to see if there are any tanks
{
totalMpg = totalMpg / tankCounter; // divide accumulated miles per gallon by # of tanks to get total mpg

document.writeln("<TR><TD><H2>Total mpg is " + totalMpg + ".</H2></TD></TR>");
document.writeln("</TABLE>");
}
else
document.writeln("<TR><TD>No numbers were entered.</TD></TR>");
 
Back
Top