How to write a while loop inside an if-else loop - javascript

Please tell me what is wrong with my code. It seems like after continue; it still loops over the same block even if I use the largest number as an input. Here it still wants me to input a larger number:
// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)
// 2) Ask the user input (reference: prompt())
let userInput = prompt(`Give me a number`)
const userInputInt = parseInt(userInput)
console.log(userInput)
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))
if(isNaN(userInput)){
prompt(`Give me a freaking number`)
}else{
let x = 0;
while (x < 4) {
console.log('hi')
console.log(userInputInt)
console.log(RanNum)
if (userInputInt == RanNum) {
console.log(`win`)
prompt('YOU GOT IT MAN')
break;
}
else if (userInputInt < RanNum) {
x = x+1 ;
prompt('Larger please')
continue;
}
else if (userInputInt > RanNum) {
x= x+1
prompt('Smaller please')
continue;
}
}
if(x > 3){alert('More than 3 times')}
}
However, this one works fine. Can someone point to me what's wrong?
// Guess the number
const randomNumber = Math.floor(Math.random() * 11);
let trials = 0;
while(trials < 4){
const guess= parseInt(prompt("Give me a number(0-10)!"));
if(isNaN(guess)){
alert("You are not inputing a number");
// Works for while-loop, for-loop, do-while loop
continue;
}
trials++;
if(guess === randomNumber){
// Equal
alert("You win!!");
// If the player wins, terminate the game
// Works for while-loop, for-loop, do-while loop
break;
}else{
// Unequal
if(guess > randomNumber){
alert("Too large!");
}else{
alert("Too small");
}
}
}
if(trials > 3){
alert("You loses");
}

You can use switch-case except if-else:
let i = 0,
solution = Math.floor(Math.random() * Math.floor(11)),
max_tries = 3;
while (nmb !== solution && i < max_tries + 1) {
if (i < max_tries) {
var nmb = Number(prompt("Put number (1 - 10): "));
switch(true) {
case nmb > solution : console.log("Smaller please"); break;
case nmb < solution : console.log("Largest please"); break;
default : console.log("YOU GOT IT MAN");
}
}
else { console.log("You lose! Number was: " + solution) }
i++
}
You only need to add outputs to the console as in your variant.

Related

Howcome when I run my code, does it infinitely repeat the same statement?

I am writing code to make a guessing game with parameters as follows: Guessing Game Prompt. Could someone please help me figure out why when I run it, it constantly outputs the same two lines infinitely and doesn't give me an opportunity to guess again? Below is the code that I have written.
var randNum = Math.random() * (50 - 0) + 0;
var userGuess = prompt ("Choose a number between 1 and 50: ");
var count = 0;
var controlNum = 0;
while (userGuess != randNum){
if (userGuess == randNum) {
controlNum = 1
console.log ("YOU GOT IT!");
console.log (count);
} else if (userGuess > randNum) {
console.log ("TOO HIGH");
console.log ("Try Agian");
count ++
} else if (userGuess < randNum) {
console.log ("TOO LOW");
console.log ("Try Again");
count ++
}
}
Thank you for your help!
You have the prompt to choose a number outside of your while loop.
Therefore, userGuess never actually changes, and it keeps comparing userGuess to randNum. That's an infinite loop (unless you get it right the first time).
Try this:
var randNum = Math.random() * (50 - 0) + 0;
var userGuess = 0;
var count = 0;
var controlNum = 0;
while (userGuess != randNum){
userGuess = prompt ("Choose a number between 1 and 50: ");
if (userGuess == randNum) {
controlNum = 1
console.log ("YOU GOT IT!");
console.log (count);
} else if (userGuess > randNum) {
console.log ("TOO HIGH");
console.log ("Try Agian");
count ++
} else if (userGuess < randNum) {
console.log ("TOO LOW");
console.log ("Try Again");
count ++
}
}
First of all, Math.random will give you number in floating-point pseudo-random number in the range 0 to less than 1. So you need to get the int part only.
Second You need to ask the user to guess again so you need to prompt again after checking all condition
var randNum = Math.floor(Math.random() * (50 - 0) + 0);
var userGuess = prompt("Choose a number between 1 and 50: ");
var count = 0;
var controlNum = 0;
while (userGuess != randNum) {
if (userGuess == randNum) {
controlNum = 1;
console.log("YOU GOT IT!");
console.log(count);
} else if (userGuess > randNum) {
console.log("TOO HIGH");
console.log("Try Agian");
count++;
} else if (userGuess < randNum) {
console.log("TOO LOW");
console.log("Try Again");
count++;
}
userGuess = prompt("Choose a number between 1 and 50: ");
}

Why does the variable always outputs 1, even though it's incremented in Javascript

I tried solving a Problem I found online. I successfully solved the problem, but there's one small error that I couldn't solve.
The Problem
Write a guessing game where the user has to guess a secret number.
After every guess the program tells the user whether their number was
too large or too small. At the end the number of tries needed should
be printed.
Here's my code:
// Generate a random number between 1 and 100
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
while(running) {
var tries = 1;
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}
Bug
Even if the user takes more than 1 try, the program still says,
Number of tries: 1
Please explain what am I doing wrong.
Thank You.
You reinitialize tires on each iteration of your while loop:
while(running) {
var tries = 1;
...
}
Try initializing outside of your loop.
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
var tries = 1;
while(running) {
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}
Your variable tries decalres inside the while body. So, any loop iteration, this variable gets the value 1. To solve this issue, you should declare & initialize the variable outside to the loop:
// Generate a random number between 1 and 100
var num = Math.floor(Math.random() * 100) + 1;
var running = true;
var tries = 1;
while (running) {
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
} else if (input > num) {
console.log("Too big");
} else if (input < num) {
console.log("Too small");
}
tries++;
}
Note: Do not use console.log(), use alert() instead. The console is for debugging, not for notify user messages.
I can see your problem. If you put a variable inside while function it will be reset each time meaning that it will be 1 each time.
If you put it outside it run just fine. Also, I believe that promt returns a string not a number that is why I would recommend you either to convert a number to string or a promt to number.
Here is the working code:
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
var tries = 1;
while(running) {
var input = parseFloat(prompt("Take a guess"));
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}

JavaScript Grading Scale Calculating error with multiple wrong answers?

I'm new to code so my mistake is probably obvious but,
When I go and test the calculator, it reads "A" then where ever the proper grade should be then Undefined. Idk where I'm going wrong.
I've tried a lot of different variations, and can't get the calculator to work properly. I'm not sure where the problem is.
function calculateGrade(grade) {if (parseInt >= "90"){
alert ("A");
}
else if (parseInt >= "80" === parseInt < "90"){
alert ("B");
}
else (parseInt >= "70" === parseInt < "80");{
alert ("C");
}
if (parseInt >= "60" === parseInt < "70"){
alert ("D");
}
else if (parseInt < "60"){
alert ("F");
}}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
Suggestions and errors in your code
You already have parsed into number, so leave the '90' quotes from the numbers.
Don't use magic names and global variables. Your function accepts the grade argument. Use it in your code.
Your if else conditions are wrong. Some of them are without else if. You can left the second part of each else if conditions.
Return the final which you expect from the function.
function calculateGrade(grade) {
let final = '';
if (grade >= 90) {
final = 'A';
} else if (grade >= 80) {
final = 'B';
} else if (grade >= 70) {
final = 'C';
} else if (grade >= 60) {
final = 'D';
} else {
final = 'F';
}
return final;
}
let inputGrade = prompt("Enter a grade:");
let parsedInt = Number.parseInt(inputGrade);
let finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
You could use a patttern with early exit and start frim the smallest value check to the greatest value.
The early exit returns a function and no more check is performed, because the function has ended with return statement.
For taking an integer value with parseInt, you should use a radix of 10, because without and with leading zero the number is treated as octal number, which you do not want.
A last advice, please do not use name of build in functions or objects or reserved words as variable names. This could lead to not proper working code and to searching without reason.
function calculateGrade(grade) {
if (grade < 50){
return "F";
}
if (grade < 60){
return "E";
}
if (grade < 70) {
return "D";
}
if (grade < 80) {
return "C";
}
if (grade < 90) {
return "B";
}
return "A";
}
var inputGrade = prompt("Enter a grade:"),
grade = parseInt(inputGrade, 10),
finalGrade = calculateGrade(grade);
console.log(finalGrade);
Try it
function calculateGrade(grade) {
if (grade < 60){
alert ("F");
}
else if (grade >= 60 && grade < 70){
alert ("D");
}
else if(grade >= 70 && grade < 80);{
alert ("C");
}
else if (grade >= 80 && grade < 90){
alert ("B");
}
else if (grade >= 90){
alert ("A");
}
}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);

for loop in javaScript not running

I have this fizzbuzz game I am working on. it works properly with the for loop commented out as in this example, but If I uncomment the for loop only the fizz condition works, and nothing else. I have a pen here: http://codepen.io/lucky500/pen/GJjVEO
//for (i = 1; i < 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
resultBox.innerHTML = "fizzbuzz";
} else if (i % 3 === 0) {
resultBox.innerHTML = "fizz";
} else if (i % 5 === 0) {
resultBox.innerHTML = "buzz";
} else if (i > 100) {
alert("Please enter a number from 1 to 100");
} else {
resultBox.innerHTML = i;
}
// clear input
input.value = " ";
}
//}
You're overwriting the content each time with:
resultBox.innerHTML = ...
You need to concat the results instead:
resultBox.innerHTML += ...
That's why you only see one (the last) output.
See it here: http://codepen.io/anon/pen/mJMKOe
(you need to fix the input though)

Guess a number game, score counter giving incorrect result

I am making a simple 1 - 10 guess the number game with Javascript.
It can be viewed here Guessing game
To add up score i have a var score = 4 which de-increments each time the number guessed (with a for loop which is smaller than 5) incorrect. I += to var tally and display tally as score.
My problem is score always equals 0, and therefore does not add anything to tally, I am struggling to find a solution.
My javascript is:
var tally;
function play() {
var compNum = (Math.random() * 10).toFixed(0);
var score = 4;
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
score--;
}
tally += score;
$("#score").html("score: " + tally);
if (i >= 3 && userNum != compNum) {
var again = confirm("Sorry you lost. The number was: " + compNum + " Play again?");
} else if (userNum == compNum) {
again = confirm("Well done! play again?");
i <= 5;
}
if (again) {
play();
}
if (userNum == "") {
i <= 5;
}
}
HTML:
<button onclick="play()">PLAY</button>
<div id="score"></div>
Your help is really appreciated
You should check whether the number entered by the use is equal to the random one and if that is the case exit form the for loop.
With your code the loop runs the whole 4 times,
In your loop, you need to check if the user has the right answer and exit the loop if they do.
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = +prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
if (userNum === compNum) {
// they guessed right, so exit the loop
break;
}
score--;
}
In addition, I'd check to see if isNaN(userNum) to check your user actually entered a number. It's up to you if you want to give them another chance if they don't.

Categories