Nested else if in javascript - javascript

In this random number guessing, after obtaining input from user, if its is wrong (it should go to else) it does not go to the else statement. I can't find where it went wrong.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
var random = Math.floor(Math.random() * 10) + 1;
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}
} else if (guessint < random) {
var guessless = prompt("Try again with value GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}
} else {
document.write("Oops Guessed wrong");
}

Assuming that both guessint and random are indeed defined numbers, then your else condition will never be reached, because when comparing one number against another the only three logical outcomes are that the first is equal, less to, or greater than, the second.

You have obscure { in last else if statement, i've hightlighted it with ___^___ in code snippet below, remove it and everything suppose to work as expected:
else if(guessint<random)
{
var guessless = prompt("Try Again With Valur GREATER than "+guessint)
if(parseInt(guessless)===random)
{
document.write("Guessed Correct Less")
}
}
___^___
else
{
document.write("Oops Guessed wrong");
}

Updated code, you need to have the else inside, updated code below.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
console.log(guessint);
var random = 4; //Math.floor(Math.random()*10)+1;
console.log(random);
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try Again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}else {
document.write("Oops Guessed wrong");
}
} else if (guessint < random) {
var guessless = prompt("Try Again With Valur GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}else {
document.write("Oops Guessed wrong");
}
}

You could use a while loop for guessing. Stay in the loop while the input value is not equal to the random value.
Inside the loop, you need to check for greater, then and prompt the user. after promting, you need to convert the value to an integer with base 10.
If the value is smaller (the else part) prompt for a new number.
If the loop id leaved, you know the guessed value is found and display the message.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !"),
guessint = parseInt(guess, 10),
random = Math.floor(Math.random() * 10) + 1;
while (guessint !== random) {
if (guessint > random) {
guessint = parseInt(prompt("Try Again with value LESSER than " + guessint), 10);
} else {
guessint = parseInt(prompt("Try Again With Valur GREATER than " + guessint), 10);
}
}
document.write("Guessed Correct");

Let's go through it step by step.
Let's say random is 10 and the user picks 9 (so guessint = 9).
Now let's replace those values on your if / else statements:
if (9 === 10) { // False!
} else if (9 > 10) { // False!
} else if (9 < 10) { // True!
/* Runs this part of the code */
} else { // It will never get to this else!
}
No matter what value the user selects, it will have to be either:
Equal to 10
Greater than 10
Lesser than 10
There is no number that will not match any of those conditions. So it will always enter one of your if statements, and never the last else.
You would need an else on every if, like Thennarasan said, or a control variable, like so:
var guessint = parseInt(prompt("Guess a value between 1 and 10!"));
var random = Math.floor(Math.random() * 10) + 1;
// Control variable
var guessed_correctly = false;
if (guessint === random) {
// Correct on first chance
guessed_correctly = true;
} else if (guessint > random) {
// Second chance
var guessgreat = prompt("Try again with a value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
} else if (guessint < random) {
// Second chance
var guessless = prompt("Try again with a value GREATER than " + guessint);
if (parseInt(guessless) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
}
if (guessed_correctly === true) {
// If the user was correct on any chance
document.write("Congratulations!");
} else {
// If the user was incorrect on both chances
document.write("Oops! Guessed wrong!");
}
Alternatively, there are other methods to implement the game you're making with whiles and such, but the example I've given is based on your format.

Related

Programming a game of guessing number - I can't get while loop to work (Javascript)

I'm programming a game where a random number from 1-20 is generated, the user guesses the number. If he guesses wrong, his score is deducted by 1 everytime (score starts at 20). When score reaches 0, the game is over.
My difficulty is getting the game to keep going while score is above 0 and stop when it's 0.
At first, I put in the while loop within the click event:
//to generate a random number
const random_number = Math.trunc(Math.random() * 20) + 1;
//display random (only for testing purpose, not in the actual game)
document.querySelector('.number').textContent = random_number;
//every player starts with 20. Everytime they guess wrong it gets deducted by 1
let score = 20;
//player input their number. Check for player input against random number generated above
document.querySelector('.check').addEventListener('click', function () {
//I put while loop here so that when score is 0 it is game over but game continues as long as score>0
while (score > 0) {
//take the player's guess
const guess = Number(document.querySelector('.guess').value);
if (!guess) {
//if it's blank
document.querySelector('.message').textContent = 'No number';
//if guess is correct, break out of the loop.
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
break;
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score; //the score displayed on the html is set to score in script
if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
break; //once it's deducted, should break out of while loop
}
}
if ((score = 0)) {
document.querySelector('.message').textContent = 'game over';
}
});
It only works once, so if I click "check" again, the game does doesn't continue.
So I tried to put while loop outside of the event:
const random_number = Math.trunc(Math.random() * 20) + 1;
//display random (only for testing purpose, not in the actual game)
document.querySelector('.number').textContent = random_number;
//every player starts with 20. Everytime they guess wrong it gets deducted by 1
let score = 20;
//putting while loop outside of event this time
while (score > 0) {
document.querySelector('.check').addEventListener('click', function () {
//take the player's guess
const guess = Number(document.querySelector('.guess').value);
if (!guess) {
//if it's blank
document.querySelector('.message').textContent = 'No number';
//if guess is correct, break out of the loop. Script works well up to here
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
//I want to put a break here but it says illegal break
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score; //the score displayed on the html is set to score in script
if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
//I want to put a break here but it says illegal break
}
});
break;
}
if ((score = 0)) {
document.querySelector('.message').textContent = 'game over';
}
This time I can play the game multiple times, but I cannot stop the while loop from running if a guess is wrong so the score ends up getting to -1 on the very first wrong guess. I try to put the break statements like before but it keeps saying 'illegal breaks'. Not sure where I'm supposed to put the breaks?
No need for a while loop. Evaluate if the score is 0 at in the else block inside your event listener. You only want to evaluate the score again whenever you subtract from it.
At the start, evaluate if the .guess field's value is empty. Doing Number('') will produce 0. That means that even if I would enter the number 0, I would get the message No number.
document.querySelector('.check').addEventListener('click', function() {
const value = document.querySelector('.guess').value;
const guess = Number(value);
if (value === '') {
document.querySelector('.message').textContent = 'No number';
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score;
if (score === 0) {
document.querySelector('.message').textContent = 'game over';
} else if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
}
});

Roll dice game if else statement not working

Here is the description of the code i need to write:
Deisgn the logic for a game that simulates rolling two dice by generating two numbers between 1 and 6 inclusive (one number for each die).
The player will choose a number between 2 and 12 (the lowest and highest totals possible for two dice).
The program will then roll the dice three times
-- if the user's guess comes up in one of the rolls the user wins.
-- If the guess does not come up computer wins.
We have not started arrays yet but I am to use a for loop and if else.
It is my if else statement that is not working.
Every roll comes up you lose.
Here is the code:
randNumber = prompt("Please enter a number between 2 and 12");
while (randNumber <= 1 || randNumber >= 13) {
alert("Input was incorrect, try again.");
randNumber = prompt("Please enter a number between 2 and 12");
}
for (var i = 0; i < 3; i++) {
computerRoll = 1 + Math.ceil(Math.random() * 11);
document.write(computerRoll + "<br>");
}
function rollDice() {
var computerRoll = rollDice(2, 12);
}
var computerRoll = rollDice;
if (randNumber == computerRoll) {
document.write("You win.");
} else {
document.write("You lose.");
}
if the computer is trying to roll 2 dice, you need 2 random numbers, both converted to range 0 to 5, and then added, and adding 2. (Try making a function to roll one die, and then calling it twice.)
The rolldice() function does not return a value. And it's computerRoll is independent of the outer computerRoll.
the outer computerRoll is set to a function, which is never equal to a number. This is why you get only losses.
if my translator is correct :
let randNumber, computerRoll
do
{
if (randNumber != undefined) {
alert('Input was incorrect, try again.')
}
randNumber = parseInt(prompt('Please enter a number between 2 and 12')) // bce promt value is string
}
while (!(1<randNumber && randNumber<13)) // to also process NaN values (not a number)
document.write('randNumber -> '+ randNumber + '<br>' )
for (let i=0;i<3;i++)
{
computerRoll = Math.floor(Math.random() *6) +1 // first dice
computerRoll += Math.floor(Math.random() *6) +1 // second dice
document.write('computerRoll -> '+ computerRoll + '<br>' )
if ( computerRoll === randNumber ) break
}
if (randNumber === computerRoll) {
document.write('You win.')
}
else {
document.write('You lose.')
}

Can't detect why my loop is infinite

var randomNum = Math.round(Math.random() * 100);
guesses = prompt("guess a number between 1 and 100");
var scores = 0;
while (randomNum < 100) {
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guesses === randomNum) {
console.log("great ... that is correct!!")
} else {
console.log("game over ... your guess was right " + scores + " times");
}
}
I have been struggling with the while loop concept for some time now and in order to confront my fears I decided to practice with some tiny exercises like the one above.
You're not incrementing randomNum hence it will always stay in an infinite loop.
You initialize randonNum and guesses at the beginning of your code, but then you never change their values again. So, once you go inside the while loop and the condition starts out to be false, then there is nothing inside the while loop to ever change the outcome of the comparison condition. Thus, the condition is always false and you end up with an infinite loop. Your loop structure boils down to this:
while (randomNum < 100) {
// randomNum never changes
// there is no code to ever break or return out of the loop
// so loop is infinite and goes on forever
}
You can fix the problem by either putting a condition in the loop that will break out of the loop with a break or return or you can modify the value of randomNum in the loop such that eventually the loop will terminate on its own.
In addition, guesses === randomNum will never be true because guesses is a string and randomNum is a number so you have to fix that comparison too.
It's not 100% clear what you want to achieve, but if you're trying to have the user repeatedly guess the number until they get it right, then you need to put a prompt() inside the while loop and a break out of the while loop when they get it right or ask to cancel:
var randomNum = Math.round(Math.random() * 100);
var guess;
var score = 0;
while ((guess = prompt("guess a number between 1 and 100")) !== null) {
// convert typed string into a number
guess = +guess;
if (guess < randomNum) {
console.log(" too low.. continue")
} else if (guess > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guess === randomNum) {
console.log("great ... that is correct!!")
console.log("score was: " + score);
// when we match, stop the while loop
break;
}
}
the below line of code of your assign randomNum only one time hence it doesn't change
var randomNum = Math.round(Math.random() * 100);
so when you are trying to create the while loop the randomNum value remains same
try changing the randomNum value in the while loop
I think this is what you tried to achieve. Retry x number of times
var randomNum = Math.round(Math.random() * 100);
var guesses;
var scores = 0;
var tries = 0
while (tries++ < 3) { // Loop if less than 3 tries, and increment
guesses = prompt("guess a number between 1 and 100");
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
} else {
// It's not to low, not to high. It must be correct
score++;
console.log("great ... that is correct!!");
randomNum = Math.round(Math.random() * 100);
}
}
console.log("game over ... your guess was right " + scores + " times");

Javascript - Find if number is positive or negative

I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.

Guessing game woes

Hello i am very new to javascript and have been trying to make a random number guessing game. I think i almost got it except there is one thing i cant figure out. Everytime i run it i have to type in my number twice and it also only returns Lower no matter what number i type in.
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
{
while (randomNumber != readline())
if (readline() < randomNumber)
{
print("Lower");
}
else if (readline() > randomNumber)
{
print("Higher");
}
else if (readline() == randomNumber)
{
print("Good Job");
}
}
Your problem is you are calling readline multiple times per iteration of your while loop. Here I have stored the value of readline into a variable and use that to test:
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
var hasGuessedCorrectly = false;
while (!hasGuessedCorrectly)
{
var guess = readline();
if (guess < randomNumber)
{
print("Lower");
}
else if (guess > randomNumber)
{
print("Higher");
}
else if (guess == randomNumber)
{
print("Good Job");
hasGuessedCorrectly = true;
}
}

Categories

Resources