PDA

View Full Version : multiple condition while loop

timewarp
Apr 17th, 2013, 06:13 PM
Hi,

Trying to create a multiple condition while loop this is what i have:

<html>
<title> fuel </title>

<body>
<script>
var capacity = parseInt(prompt("Enter amount of gallons:",100));
var mpg = parseInt(prompt("Enter mpg:",100));
var price = parseFloat(prompt("Enter price of a gallon of petrol:"));
while (((capacity <=6 && capacity <=20) mpg <=20 && mpg <=75) price < 3.20 && 4.20) {

var eco = capacity * mpg;
var cost = (100 / mpg * price);
document.write("The car will travel: "+ eco + " : " + "the cost of travel is : " + cost);
mpg = 0;
price = 0;
capacity = 0;

}

</script>

</body>
</html>

not sure where ive gone wrong as i haven't done one before,
the conditions are that: gallons must be between 6 and 20
efficiency must be between 20 and 75
price must be between £3.20 and £4.20

Any help would be appreciated

thanks

Philip M
Apr 17th, 2013, 06:35 PM
Sounds like homework!

A while loop is used to do a calculation repeatedly so long as some condition is true. You want to do the calculation once only. So you need to use an if statement.

But why these conditions? If there are some limits to gallons, efficiency and price you should check that the values entered fall into the acceptable range at the time the user enters them. Not at the time the calculation is being performed. What happens if the user enters out-of-range values, or NaN entries?

To answer your question, yes, you may have multiple conditions for a while statement. Use && to define the conditions.

<script type = "text/javascript">

var a = 3;
var b = 6;

while ((a<=10) && (b <=10)) {
document.write((a*b) + "<br>");
a++;
b++;
}

// Results:- 18 28 40 54 70

</script>

If you want to use a while loop to ensure that a valid number is entered:-

<script type = "text/javascript">

var repeat = true;
while(repeat) {
var ans = Number(prompt("Enter a positive number max.100","")); // use Math.floor() if an integer number is required.
if ((isNaN(ans)) || (ans == null) || (ans < 0) || (ans > 100)) {
alert ("You must enter a positive number max. 100");
}
else {
repeat = false;
}
}

</script>
Be aware that prompts and document.write() are long obsolete and should only be used for testing or demonstration purposes.. Ask your teacher to update his knowledge of Javascript into the 21st Century.

Rather than parseInt() which is intended to convert numbers fom one base to another, use Math.floor(). And prefer to use use Number() in place of parseFloat().

“A man ceases to be a beginner in any given science and becomes a master in that science when he has
learned that he is going to be a beginner all his life.” Robin G. Collingwood (English Philosopher, 1889-1943)