How to fix my while loop with if statements in Javascript - javascript

Hey i am working on a guessing game project with javascript that entails inputing a number into a prompt "Give me a number between 1 and 10." Instructions are to incorporate the following:
while the guess is not equal to the target
Prompt for a new guess
If the guess is less than the target
print "too low!"
else If the guess is greater than the target
print "too high!"
else
print "You got it!"
So I have my while loop and if conditional statements but i don't know how to contain my if statements inside my while loop. My actual results just prompts me to Guess again repeatedly without alerting too high! or too low! My else statement when guessing the right number seems to work though. Thank you.
let min = 1;
let max = 10;
let target = Math.random() * (max - min + 1);
target = Math.floor(target) + min;
let guess = (0);
guess = prompt("Give me a number between 1 and 10");
console.log("Your guess is" + guess);
while (guess != target) {
prompt("Guess again");
console.log(guess);
}
if (guess < target) {
alert("too low!");
console.log("too low guess", guess);
} else if (guess > target) {
alert("too high!");
console.log("too high guess", guess);
} else {
alert("You got it!");
}

Your code is currently doing this:
Forever: ask "guess again"
After 'forever' is over (which is never!) check the value of guess. Furthermore, the value of guess is the same as the first time the question as asked.
You'll want this:
Forever: ask "guess again"
After "guess again", check and store the stored value of the last answer.
If the answer is correct stop the forever running loop.
But what is also important: make sure prompt returns a number, because anything could be entered in a text prompt.
So that would be:
// See Note 1.
guess = parseInt(prompt("Give me a number between 1 and 10"), 10);
console.log("Your guess is" + guess);
// 1. Do something forever
while (guess != target){
// 2. store the last answer
guess = parseInt(prompt("Guess again"), 10);
console.log(guess);
// 2b. check the last answer
if (guess < target){
alert("too low!");
console.log("too low guess", guess);
}else if (guess > target){
alert("too high!");
console.log("too high guess", guess);
}
// 3. If the answer is correct, `guess === target` so the loop will end.
}
// See Note 2.
alert("You got it!");
Note 1: If the player enters something that can't be turned into an integer, parseInt(, 10) will return NaN (not a number). You can test that: isNaN(123) / isNaN(NaN).
Note 2: Your application will not show a message if the player gets it correct in one go, because "you got it" was inside the loop. If the answer was right the first time, the loop would never be entered. Put the message outside the loop to fix that.

Related

How to make "case 3" into some sort of "case random"

I'm completing something for an assignment in my coding course, but I am stuck on a part of trying to set a number to random. Also, there are 3 blocks that have this, except the last block does not have an event.stopPropagation();.
I have tried setting "case 3" (which needs to be edited to something else) to "case random" but that did not work. It would only make it so that anything you would type in the prompt() would display the "You got it!" message.
...
alert( "Guess the number I'm thinking. It's between 1 and 5. You have 3 tries." )
var min = 1;
var max = 5;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
prompt( "You have 3 tries remaning." );
switch ( random )
{
case 3: alert( "You got it!");
event.stopPropagation();
break;
default: alert( "That is incorrect. Try again." );
break;
}
...
I expect it to set a random (whole) number and have the user able to guess it, and have it validate properly.
Also, if there is anything else wrong with this block of code, could you please help me?
You need to get the user's input - the prompt is an orphaned expression.
var guess = +prompt(...);
Then switch on the guess:
switch(guess) {
case random:
alert("You got it!");
event.stopPropagation();
break;
default:
alert("That is incorrect. Try again");
break;
}
Switching isn't the best practice here however - as Barmar points out, an if is better and easier:
if (guess == random) {
alert("You got it!");
event.stopPropagation();
} else {
alert("That is incorrect. Try again");
}

JavaScript Function not passing variable

My game here is a guessing game, which counts the number of guess and does not include any repeated guesses.
I am trying to pass the variable tries from function attempts to function tries but it will not work. The count remains 0, but when I pass sameGuess.length it work, why is this?
let random = Math.round(Math.random()*100);
let guess = false;
let sameGuess = []
let tries = sameGuess.length;
function game(){
while (guess === false){
let myGuess = prompt('Guess a number between 0-100:');
numCheck(myGuess);
if (myGuess == random){
guess = true;
repeats(myGuess, sameGuess);
attempts(tries, sameGuess);
}else if (myGuess < random){
repeats(myGuess, sameGuess);
alert('Your number was too small, try again!');
guess = false;
}else if (myGuess > random){
repeats(myGuess, sameGuess);
alert('Your answer was too big, try again!');
guess = false;
}
}
}
function attempts(tries, sameGuess){
if (sameGuess.length == 1){
alert('Well done, you got it frist try!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length <= 15){
alert('You took ' + sameGuess.length + ' tries');
alert('Well done, you didn\'t take too many tries!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length >=16){
alert('You took ' + sameGuess.length + ' tries');
alert('You got it, but lets see less tries next time!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}
}
function repeats(myGuess, sameGuess){
if ((sameGuess.indexOf(myGuess)) == -1){
(sameGuess.push(myGuess));
}else alert('You have already guessed that number! - Dont worry, i haven\'t counted it!');
}
function numCheck(myGuess){
if (isNaN(myGuess)){
alert('Enter a number, don\'t try and be sneaky!');
}
}
game ();
When you access array.length, that value is copied, meaning it won't update even after you add a value to the array:
var array = [];
var length = array.length;
console.log(length); // 0
array.push('Some value');
console.log(length); // Still 0, since it was copied, it is _not_ a reference to the live value
console.log(array.length); // 1, this is a live reference to the length of the array
As it stands now, your code works fine, although it looks like you can remove the tries aspect of it and use the sameGuess.length directly, as you are now.
See this post for more discussion on Pass by Reference or Pass by Value.
You should put tries = sameGuess.length; inside of your while!

else statement within nested if statements. How does this code know which else statement to execute?

I get the nested if loops (same as using && operator), but how does this code here know which conditions to execute with no conditions and just back to back else statements? One of them is within the nested if statements. I can tell that's obviously why this works the way it does, I just don't get how. Also, I know how to write this in several more readable ways testing multiple conditions. Please just explain what is happening with this code here. How does it know to output "You are too old" or "You are too young?"
var age = prompt("Please enter Your age here :");
var min_age=18;
var max_age=40;
if(age>=min_age){
if(age<=max_age){
console.log("You meet the requirements for this competition");
}else{
console.log("You are too old");
}
}else{
console.log("You are too young");
}
The if-then-else ambiguity is known for a long time. All languages have solved it by defining that an else will match the first perceding if. So:
if (a)
if (b)
x = 1;
else
x = 2;
resolves to:
if (a) {
if (b) {
x = 1;
}
else {
x = 2;
}
}
EDIT by Nisar's reuest:
The if statement is defined as:
if (<condition>) <statement> [else <statement>]
This means that a <statement> in the above may also be an if statement. So, for example:
if (<condition>) if (<condition>) [else <statement>] [else <statement>]
As each else part is optional, the compiler has no way of knowing when it sees an else part to which if it belongs. To solve that the language defines that an else always matches the first preceding if.
The brackets {} set the limit.
Try to think in pseudocode, look beyond the characters and think about what is happening.
Reading in order:
If you are old enough
If your are not too old
'You meet the requirements for this competition'
OTHERWISE
'You are too old'
END
OTHERWISE
'You are too young'
END
Note how indentation can help see the limits of the conditions. Each indented part can be separated.
Firstly, let's indent your code.
var age = prompt("Please enter Your age here :");
var min_age = 18;
var max_age = 40;
if (age >= min_age)
{
if (age <= max_age)
{
console.log("You meet the requirements for this competition");
}
else
{
console.log("You are too old");
}
}
else
{
console.log("You are too young");
}
Starting off..
var age = prompt("Please enter Your age here :");
Let's say you enter 21 in the prompt box, so age=21
We initialize
var min_age = 18;
var max_age = 40;
Now let's look at the first if condition.
if (age >= min_age)
If you substitute the values,this translates to
if (21 >= 18)
This is true,therefore we go inside the if block and not to the else.
The next line is.
if (age <= max_age)
This translates to
if (21 <= 40)
Considering this is also true, we print You meet the requirements for this competition.
The most important take-away from this is, indent your code, and the rest becomes pretty simple.
There are just 3 Options
too young
correct age
too old
First Check - is the person old enough?
if(age>=min_age)
Second check - is the person too old?
if(age<=max_age)
the only possible option left after this if statment is FALSE :
too old

Using JS to check if integer is even or pressing q to quit

The objective here is for the user to enter a number to determine whether it is even or to enter 'q' to quit the program.
var readlineSync = require('readline-sync');
var i = 0;
while (i <= 3) {
var num = readlineSync.question("Enter q to quit, or enter an integer to continue?");
if (num === 'q') {
console.log("You have quit the application. Thanks for using.");
break;
}
else if (num % 2) {
console.log("You have entered an odd number");
}
else if (num !== 'q') {
console.log("You have not entered a valid character. Please try again.");
break;
}
else {
console.log("You have entered an even number.");
break;
}
}
Pressing q initiates the appropriate response and exits the program. Entering an odd number also generates the appropriate response. However if an even number is entered, the program does not generate the appropriate response and instead reads You have not entered a valid character. Please try again. What am I overlooking? Any advice is appreciated.
It's because of your third condition (num !== 'q'). It evaluates as true when you enter an even number.

Count the number of times an input has been made javascript

What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.

Categories