Attempting to nest if/else statement in while loop - javascript

I'm setting up the following while loop to continue to print a message for each even number entered but print a different message for an odd number and stop:
userEnteredNumber = prompt("Please enter a number:");
while (userEnteredNumber%2 === 0) {
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
}
userEnteredNumber = prompt("Please enter a number:");
console.log(userEnteredNumber);
}
Right now it will continue to print with even number entry and stop if an odd number is entered, but the odd number message won't print. Not really understanding why the odd message won't print. Hoping someone can help clarify it for me!

More like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber == null) { // they clicked cancel
break;
}
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
} else {
document.write(NOT_VALID_MESSAGE + userEnteredNumber);
}
console.log(userEnteredNumber);
}

From your code, you can change it a bit to look like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
break;
}
console.log(userEnteredNumber);
}

Related

What am i doing wrong? it wont run thru every condition

I'm trying to have someone guess a number from 1 to 6. I give them two tries if, by the end of the second try, they don't get it, then else will tell them what the number is but it just won't run. what am I doing wrong?
var number = Math.floor(Math.random() *6) +1;
var answer = false;
var guess = prompt('Take a guess, pick a number from 1 to 6');
if(parseInt(guess) === number) {
answer === true;
} else if (parseInt(guess) > number) {
var guessLess = prompt('To high! Guess less');
if (parseInt(guessLess) === number) {
answer === true;
} else if (parseInt(guess) < number) {
var guessMore = prompt('Guess more');
if(parseInt(guessMore) === number) {
answer = true;
}
}
}
if (answer) {
alert('You got it')
} else {
alert('No. The number was ' + number);
}
}
You are using comparison instead of assignment in the below segment
if (parseInt(guessLess) === number) {
answer === true;
Change it to
if (parseInt(guessLess) === number) {
answer = true;

random number doesn't change in loop

The random number doesn't change using while loop. When I want to play again, the randomnumber is still the same.
Here's the code:
randomnumber=Math.floor(Math.random()*10);
while(true){
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
You should repeat the generation of the random number when a next game is requested:
var randomnumber = Math.floor(Math.random()*10);
while (true) {
var yourguess = prompt("Please Enter A Number Between 1-10");
if (randomnumber == yourguess) {
alert("Good Job");
var answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
randomnumber = Math.floor(Math.random()*10); //<---
} else {
break;
}
} else {
alert("Not Matched "+ randomnumber);
}
}
Make sure to declare your variables (with var, let or const).
You need to generate that randomnumber inside the while loop:
while(true){
var randomnumber=Math.floor(Math.random()*10);
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
If you want a different random number each time the loop is executed, you need to generate the randomnumber inside the while loop.
while (true) {
let randomnumber = Math.floor(Math.random() * 10);
yourguess = prompt("Please Enter A Number
Between 1 - 10");
if (randomnumber == yourguess) {
alert("Good Job");
answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
} else {
break;
}
} else {
alert("Not Matched " + randomnumber);
}
}
You could make randomnumber a function and call it on loop start. In addition your code snippet was changed a bit in order not to get stuck in a loop of un-closing prompt windows, what was missing is a small part that checks what happens when user does not provide an answer or clicks the cancel button.
var randomnumber = function() { return Math.floor(Math.random()*10); }
while(true){
let number = randomnumber();
yourguess=prompt("Please Enter A Number Between 1-10");
if(!yourguess) {
break;
}
if(number===parseInt(yourguess)){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N");
if(!RegExp("y","gi").test(answer) || !answer){
break;
}
}else{
alert("Not Matched "+ number);
}
}

Javascript Prompt Box Loops

Something is wrong with this code but I can't figure out what it is. The page does not work properly or do what it's supposed to. I need a code that prompts for a password and that limits the attempts to 3. After the third attempt, it needs to have an alert box.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts = 0)
{
alert("Incorrect Password");
}
</script>
You have a couple of issues. You should check entry after the user enters in the prompt. Or the last entry will not be checked. Next issue is you are not exiting the loop. Another issue is the fact that = is assignment so inside the if you are assigning zero, not checking to see if it is zero.
var attempts = 3;
while (attempts > 0) {
var answer = prompt("Password: ");
if (answer == "Psycho") {
document.write("These are pictures of my kitten and her things.");
break;
}
attempts--;
}
if (attempts == 0) {
alert("Incorrect Password");
}
There are a few options to fix your code.
You could return once you're done the work.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
break;
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts == 0)
{
alert("Incorrect Password");
}
</script>
Or, I would return early if you've failed
<script>
var attempts = 4;
var answer = prompt("Password: ");
while (attempts > 0 && answer != "Psycho")
{
answer = prompt("Password: ");
attempts--;
}
if (attempts == 0)
{
alert("Incorrect Password");
}
else
{
document.write("These are pictures of my kitten and her things.");
}
</script>

code stops looping

My code is not working properly. It is not continuing the loop. It is just showing that your value is low or high and stopping it there. Why doesn't it keep looping?
var target;
var count = 0;
var play;
var game;
function do_this() {
var choose = (Math.floor(Math.random() * 100));
target = choose + 1;
while (true) {
play = prompt("I am thinking of a no. between 1 and 100\n\n" + "enter the no.");
game = parseInt(play);
count = count + 1;
if (isNaN(game)) {
alert("Please enter integer value");
return false;
}
if ((game < 1) || (game > 100)) {
alert("Please enter the value between 1 and 100");
return false;
}
if (game < choose) {
alert("enter higher value");
return false;
}
if (game > choose) {
alert("enter lower value");
return false;
}
alert("You are correct\n\n" + "you took" + count + "to guess the game");
return true;
}
}
do_this()
You are using return false; when the value is higher or lower. Replace that with continue;

How to debug a console Hangman program?

This program takes sentence as user input. Then it randomly selects word of hangman game. After user is asked to enter letters one by one. I believe there is something wrong with my function guess. It does not behave like I wanted to.
Guess function suppose to do guess(letter). If letter hasn't been tried already, push the letter tried into the array of guessedLetters and decrease guesses by 1. Loop through currentWord to see if letter is a match. If it is, assign letter to appropriate spots in hangmanWord.
If isOver returns true, invoke overMessage, else invoke render, prompt a new letter and invoke guess with that letter (using recursion).
var numOfGuesses;
var gueesedLetters = []
var currentWord = ''
var hangmanWord = []
var letter;
function guess(letter) {
if (gueesedLetters.indexOf(letter) === -1) {
gueesedLetters.push(letter);
numOfGuesses--;
}
else {
for (var i = 0; i < currentWord.length; i++) {
if (letter === currentWord[i]) {
var currWrdIndex = currentWord.indexOf(letter)
hangmanWord.splice(currentWord[i], 0, letter)
}
}
}
if (isOver() === true) {
overMessage();
} else {
console.log(render());
letter = prompt("Please enter the letter").toLowerCase();
guess(letter);
}
}
function isOver() {
if (currentWord.split("").sort().join("") === hangmanWord.sort().join("") || numOfGuesses === 0) {
return true
} else {
return false
}
}
function overMessage() {
if (currentWord.split().sort().join("") === hangmanWord.sort().join("")) {
return "You win";
} else if (numOfGuesses === 0) {
return "You lose";
} else {
return "Game is not over";
}
}
function render() {
console.log("The hangman word was %s", currentWord);
console.log("The total number of guesses are %s", numOfGuesses);
console.log("Total guess letters are %s", gueesedLetters);
}
function startGame(wordsArray) {
numOfGuesses = 10;
gueesedLetters = []
currentWord = wordsArray[Math.floor(Math.random() * wordsArray.length)]
letter = prompt("Please enter the letter ?")
guess(letter);
}
function mainProgram() {
var userSentence = prompt("Please enter sentences to begin.")
userSentence = userSentence.split(" ")
startGame(userSentence)
if (isOver() === true) {
console.log(overMessage())
console.log(render())
}
}
mainProgram()

Categories

Resources