I’m just starting to learn javascript but it just drives me crazy! This is a question to enter a boot camp for learning javascript because I’ trying to change my career.
Here I have the variable target that is a number up to 10 and I need to write a program that will keep on guessing numbers and printing them until it is the target number. I have five tries, but if I guess it first, it should print a message and break out of the loop, but I simply don’t know what is wrong with it, it keeps giving me some error
var target = Math.ceil(Math.random() * 10);
var guess = Math.ceil(Math.random() * 10);
var tries=5;
console.log ('Target is '+target);
console.log('You have '+tries+' tries');
if (guess==target){
console.log('Congratulations! The number ' + guess +' is right!');
}
else{
while (tries>0){
guess = Math.ceil(Math.random() * 10);
console.log('Number '+guess +' is wrong');
tries --;
console.log('You still have ' +tries + ' tries');
if (guess==target){
console.log('Congratulations! The number ' + guess +' is right!');
break;
}
if (tries==0){
console.log('You had your chance');
}
}
}
Are you looking for an error in the code you posted (which works, btw but may not be the most effective) or the code in the screenshot? The code in the screenshot is throwing the error because the while statement is doing two checks (and won’t show the right message if it’s correct)
I’m looking for errors in both ways because neither is working. I know they are both messy, I tried cleaning it a bit.
This is my last atempt
var target = Math.ceil(Math.random() * 10);
var guess;
var tries = 5;
console.log("Target is " + target);
console.log('You have '+tries+' tries');
while (tries > 0) {
guess = Math.ceil(Math.random() * 10);
if (guess === target) {
console.log('Congratulations! Guess '+guess+' is correct!');
break;
}
tries--;
console.log('Guess '+guess+' is wrong. You still have '+tries+' guess(es)');
if (tries === 0) {
console.log("you lose");
}
}
It gives this error: >>>>Code is incorrect Make you you’re printing the value of guess to the console in the line below assigning it a new value
If I move both of them it doesn’t work, if I move just the deprecator it says: >>>>Code is incorrect Make sure you’re decrementing the value the variable tries after generating and print a new guess
var target = Math.ceil(Math.random() * 10);
var guess;
var tries = 5;
console.log("Target is " + target);
console.log('You have '+tries+' tries');
while (tries > 0) {
guess = Math.ceil(Math.random() * 10);
console.log(guess);
if (guess === target) {
console.log('Congratulations! Guess '+guess+' is correct!');
break;
}
tries--;
}
You need first atribuite the new value to guess in the first while line and print. Then you need to decrement tries value.
Use if to confirm the guess value is equal target value and break the loop.