I am taking a Javascript class and I'm working on my own project. I am currently stuck on a for loop and was hoping someone could help.
This is the code I have written:
console.log(`-----WATER REFILL STRATEGY-----`);
console.log(totalWaterToDrink, waterPerHour(raceInfo.tempHigh));
let waterHourFinal = waterPerHour(raceInfo.tempHigh);
console.log(waterHourFinal);
for (let j = totalWaterToDrink; j > 0; j - waterHourFinal) {
console.log(`${j - waterHourFinal} water left`);
}
for (let i = 0; i < raceTime; i ) {
console.log(`Hour ${i 1}: drink $INPUT OZ PER HR HERE.`);
}
The problem exists with the For loop involving J. I get an infinite output and I am not sure why.
This is literally my first coding question to the public ever so be nice. ;)
Thanks! (and if there is a better way to ask questions, please let me know)
My code:
The output:
CodePudding user response:
You need to use -=
instead of -
for (let j = totalWaterToDrink; j > 0; j -= waterHourFinal) {
console.log(`${j - waterHourFinal} water left`);
}
CodePudding user response:
You need to write j = j - waterHourFinal
instead of j - waterHourFinal
for (let j = totalWaterToDrink; j > 0; j -= waterHourFinal) {
console.log(`${j - waterHourFinal} water left`);
}
Short hand for j = j - waterHourFinal
could be j -= waterHourFinal
CodePudding user response:
You should study the for
loop better
for (let j = totalWaterToDrink; j > 0; j - waterHourFinal) {
console.log(`${j - waterHourFinal} water left`);
}
I think the j > 0;
is wrong
When you say greater than 0, the loop continues till infinity. You should use something like for (let j = 0; j < totalWaterToDrink; j--)
Also the for
loop takes three values init;condition;increment_or_decrement; where increment_or_decrement is usually handled by or --
I hope you find this useful :).