Reputation: 165
I'm new to Javascript, and I'm trying to wrap my head around while loops. I understand their purpose, and I think I understand how they work, but I'm having trouble with them.
I want the while value to repeat itself until two random numbers match each other. Currently, the while loop only runs once, and I need to run it again if I want it to repeat itself.
How can I set this loop up so that it will automatically repeat the if statement until diceRollValue === compGuess? Thanks.
diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
whileValue = true;
while (whileValue) {
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
whileValue = false;
}
}
Upvotes: 2
Views: 537
Reputation: 21
Put the 2 random variables inside the loop.
whileValue = true;
while (whileValue) {
diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
}
}
Upvotes: 1
Reputation: 101604
That's because you're only executing the random number generator outside of the while. If you want two fresh numbers they need to be executed within the while statement. Something like the following:
var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7),
whileValue = true;
while (whileValue){
if (diceRollValue == compGuess){
console.log('Computer got it right!');
whileValue = false; // exit while
} else {
console.log('Wrong. Value was ' + diceRollValue);
diceRollValue = Math.floor(Math.random() * 7); // Grab new number
//whileValue = true; // no need for this; as long as it's true
// we're still within the while statement
}
}
If you wanted to refactor it, you can use break
to quit the loop (instead of using a variable) as well:
var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7);
while (true){
if (diceRollValue == compGuess){
// breaking now prevents the code below from executing
// which is why the "success" message can reside outside of the loop.
break;
}
compGuess = Math.floor(Math.random() * 7);
console.log('Wrong. Value was ' + diceRollValue);
}
console.log('Computer got it right!');
Upvotes: 6
Reputation: 97672
You have two problems, the first is that you are setting whileValue
in both the if and the else blocks so the loop will break after one iteration regardless of the values of the random numbers.
Secondly you're generating the guess before the loop so you'd be checking the same values over and over.
So remove whileValue
assignment in the else block and move the compGuess
assignment into the while loop.
Upvotes: 1