How to ask a user to guess a number between 1 - 1000 - javascript

I'm trying to write some javascript code that asks the user to guess a number from 1 to 1000 and enter it into the prompt box. If the user guesses right, an alert box will pop up saying they got it right. If they guess wrong, another alert box will popup and say that they are wrong and to try once more.
The issue here is that I don't know what I have to do to make the code loop infinitely until they get the right answer. Here's what i have so far:
var a = 489; // the number that needs to be guessed to win the game.
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}

Number matching
Basically, when you make prompt, it returns a String or text, not a number. To fix this, do:
if (parseInt(b,10) === a) {
//Code
}
Other ways
They're a lot of ways to parse numbers. Here's a few more:
parseFloat(b); // Also parses decimals: '5.3' -> 5.3
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
+b; // A very 'short' way; '5.4' -> 5.4
Number('5.4e2'); // Number case: '5.4e2' -> 540
Looping
Now to repeat? Make it a loop!
var a = 432;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a){
alert("You're right!");
break; // Stops loop
} else if (!b) { break; }
else {
alert("Incorrect! Try again!");
}
}
Not sure why, but some people hate while true loops. They shouldn't cause any problems as long as you coded it properly
Random Numbers
You can get a random number using Math.random.
var min = 1,
max = 1000;
Math.floor(Math.random() * (max - min + 1)) + min;
If you're like me and want short code, you can shorten it by:
Math.floor(Math.random() * (999)) + 1;
All Together Now!
var a = Math.floor(Math.random() * (999)) + 1;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
break; // Stops loop
} else if (!b) {
alert("The Correct Answer was: " + a); //Shows correct answer
break;
} else {
alert("Incorrect! Try again!");
}
}

Just stick your prompt in some kind of loop. The code will inside the loop will run over and over until the comparison is false.
Basic example:
http://jsfiddle.net/s2he1twj/
var a = 500,
b;
while (parseInt(b) !== a) {
b = prompt('Enter a number!');
if (b === null) break;
}
while loop

Do this recursively by calling the same function like
var a = 489;
function promptGuess(){
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a){
alert("You're right!");
} else {
alert("Incorrect! Try again!");
promptGuess();
}
}
promptGuess();

Use a while until the match:
var a = 489;
var b;
while(b != a) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
}
One more thing: although the b != a evaluation is correct, it's error-prone. The != operator do conversion type, whilst the !== operator compares types and value.
In your case: 5 != '5' will return false, but 5 !== '5' returns true. It's recommended that your comparisons be conversion-free. It's more strict.
In your case, this means:
while(parseInt(b) !== a)
Greetings!

Related

how do I toggle a part of code that has an if-else statement?

if i have a certain part of code I want to be flipped on and off, and I have a line of code that does that, why doesn't it want to work?
let b = Math.floor(Math.random() * 10)
let a = Math.floor(Math.random() * 10)
let x = true
if (x = true) {if (a >= 5) {if (b >= 5) {console.log('test 1'} else {console.log('test 2')}} else {console.log('test 3'} else {console.log('test 4')}
i tried something like that but on a larger scale, like maybe 5 of those for a game i was attempting to make, and i was hoping that the output would be something in the console like 'test 1', but all that was showing up was an error message.
The if statement doesn't work because the comparison operator in Javascript is the triple equal sign and your code uses a single equal sign.
Also, there are some problems with your code that prevent it from running. These would generate errors.
unmatched parentheses
unmatched curly braces
else not structured quite right
And some problems that are bad form
missing semicolons
formatting is a bit difficult to read
So I took some liberties and did some refactoring. You can see the code executing below. Hope this is useful to you.
window.onload = function(){
let a = Math.floor(Math.random() * 10);
console.log(`a = ${a}`);
let x = true;
if (x === true)
{
if (a >= 5) {
console.log('a >= 5');
} else if (a >= 4) {
console.log('a >= 4');
} else if (a >= 3) {
console.log('a >= 3');
} else {
console.log('a is less than 3');
}
} else {
console.log('x is false');
}
};

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

How to run a program forever?

I've got got a stupid question, can you help me please?
I want this program to run and run and run. At this moment after each try I have to refresh page to play again and it sucks.
"8. Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number. If the user input matches with guess number, the program will display a message "Good Work" otherwise display a message "Not matched"."
Here's what I've got:
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Looser! The number was " + randomNumber);
};
Put it in an endless loop:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
but, I wouldn't do that. I'd offer a way to get out:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (!guessNumber) { // ***
break; // ***
} // ***
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
If the user presses Esc at the prompt, guessNumber will be "" or null (depending on the browser), both of which are falsy, so you'll break out of the loop.
Side note: "Loser" has only one "o" in it, and control-flow statements with attached blocks don't have ; after the block.
Put all of your code into the while (true) loop.
just make an infinite loop
var run = true
while (run)
{
console.log('foobar');
}
never set run as false and your loop will never stop

Alert displays the wrong message when running the code

I am following a Javascript track on Teamtreehouse and I trying to make a game. It asks the user to guess a number between 1 and 6 and. The user can either guess the number, type smaller one and get another chance, type a bigger one and get another chance or not guess it at all.
var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6) +1;
var guess = prompt("I am thinking of a number between 1 and 6. What is it?");
if (parseInt(guess) === randomNumber) {
correctGuess = true;}
else if (parseInt(guess) < randomNumber) {
var guessMore = prompt("Try again! The value I am thinking of is lower than " + guess);
if (parseInt(guessMore) === randomNumber ) {
correctGuess =true;}
} else if (parseInt(guess) > randomNumber) {
var guessLess = prompt("Try again! The number I am thinking of is smaller than " + guess);
if (parseInt(guessLess) === randomNumber) {
correctGuess = true; }
}
if ( correctGuess) {
alert("Yey!");
} else {
alert("Better luck next time! The number was " + randomNumber);
};
Although the code seems fine to me, every 1 our of 5 times (let's say) it displays an anomaly (although the user the guessed the number, it runs the else statement; or it asks you for a smaller number only to find out that the result was in fact a bigger number etc). You have to run to run the code a few times to see what I mean. What am I doing wrong?
So your problem with:
or it asks you for a smaller number only to find out that the result
was in fact a bigger number etc)
This is due to the fact that you have both "lower than" and "smaller than" in your conditional statement. I changed "lower than" to "greater than".
else if (parseInt(guess) < randomNumber) {
var guessMore = prompt(
"Try again! The value I am thinking of is greater than " + guess);
if (parseInt(guessMore) === randomNumber ) {
correctGuess =true;}
}
else if (parseInt(guess) > randomNumber) {
var guessLess = prompt(
"Try again! The number I am thinking of is smaller than " + guess);
if (parseInt(guessLess) === randomNumber) {
correctGuess = true; }
}
https://jsfiddle.net/7yhhfv6g/4/

determining var type from prompt command and if else statement

I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/

Categories