简体   繁体   中英

Having trouble with 'while' loop in javascript

I'm new with javascript, and I'm having some trouble understanding why this code doesn't execute:

var weight;

wight=parseInt(prompt("Please, enter weight");

while(weight>0);

{ 
  if (weight>199 && weight<300);
{

  document.write("Tax will be" + weight*5);
}

  else 
{

  document.write("Tax will be" + weight*10);
}
}

Edit: I'm sorry, I mispelled some 'weights' while writing down the code here. Either way, that's not the problem. When I run this in google chrome, it just doesn't prompt. And when it prompted, it doesn't execute the 'if' statement.

while (wight>0);

The semicolon effectively makes that loop: while wight is greater than 0, do nothing. This forces an infinite loop, which is why the rest of your code doesn't execute.

Also, 'wight' is not the same as 'weight'. This is another error.

Furthermore, if you change that line to while (weight > 0) , you will still have an infinite loop, because the code that then executes does not alter 'weight' - thus, it will always be greater than 0 (unless a number less than 0 was entered at the prompt, in which case it won't execute at all).

What you want is:

var weight;
weight=parseInt(prompt("Please, enter weight")); // Missing parenthesis
// Those two lines can be combined:
//var weight = parseInt(prompt("Please, enter weight"));

while(weight>0)
{ 
    if (weight>199 && weight<300)// REMOVE semicolon - has same effect - 'do nothing'
    {
        document.write("Tax will be" + weight*5);
        // above string probably needs to have a space at the end:
        // "Tax will be " - to avoid be5 (word smashed together with number)
        // Same applies below
    }
    else 
    {
        document.write("Tax will be" + weight*10);
    }
}

That is syntactically correct. You still need to either change the while condition, or alter 'weight' within that loop, to avoid an infinite loop.

spelling of weight :

while (wight>0);

while (weight>0);

also in

document.write("Tax will be" + wight*10);

document.write("Tax will be" + weight*10);

Try this

var weight;

weight=parseInt(prompt("Please, enter weight"));

while (weight>0)
{ 
  if (weight>199 && weight<300)
{
  document.write("Tax will be" + weight*5);
}
  else 
{
  document.write("Tax will be" + weight*10);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM