I have been asked to make a prompt to enter your current weight and target weight. The loop should calculate how many weeks it will take to reach target weight at loss of 1.38 a week. My prompts work but the loop breaks the javascript. My code is below, can someone help me out? I am new to javscript by the way.
var current_weight = prompt("Please enter your current weight",0.0);
var target_weight = prompt("Please enter your target weight",0.0);
var weeks = 0;
if(current_weight > 0 target_weight > 0){
if(current_weight > target_weight){
while(current_weight <= target weight){
var current_weight = current_weight – 1.38;
weeks = weeks + 1;
alert("it will take" + weeks + "weeks to hit target");
}
}
else if(current_weight > 0 && target_weight > 1){
alert("Current weight must be more than target weight");
}
else{
alert("Input error")
}
</script>
The loop breaks the javascript.
1 Answer 1
4 problems in your code:
missing
&&operator between the conditions in first if statementprompt returns the user entered value as string. So you can't subtract
1.38fromcurrent_weightascurrent_weightwill be a string. You need to convert user entered values in to numbersThere's a logical error in your code. You have this if statement
if(current_weight > target_weight)and if it evaluates to true, thenwhile loopcheckswhile(current_weight <= target weight)which is opposite to the condition of the wrapping if statement. Consequently, your loop will never run. You probably want loop condition to becurrent_weight > target_weightalert should be outside the while loop
var current_weight = Number(prompt("Please enter your current weight", 0.0));
var target_weight = Number(prompt("Please enter your target weight", 0.0));
var weeks = 0;
if (current_weight > 0 && target_weight > 0) {
if (current_weight > target_weight) {
while (current_weight > target_weight) {
current_weight = current_weight - 1.38;
weeks = weeks + 1;
}
alert("it will take" + weeks + "weeks to hit target");
} else if (current_weight > 0 && target_weight > 1) {
alert("Current weight must be more than target weight");
} else {
alert("Input error");
}
}
if (current_weight > target_weight) {while( current_weight <= target weight) { ...