Javascript Guessing Game - Counter Not Working - javascript

I am trying to create a Javascript guessing game where the user has 10 tries to guess a number between 1-999. I have to use a validate the number, use a loop and show alerts if the user gets a match and also when they run out of guesses. Using the number 45 just for testing. Each guess should be numbered and displayed using innerHTML. Problem is, the counter is stuck at zero. Not sure what I'm missing! Code below:
function myFunction() {
var userInput = document.getElementById("input").value;
var randomNum = 45;
// test for valid input number from 1 to 999
if (userInput < 0 || userInput > 999) {
alert("Your number must be from 1 to 999");
} else {
alert("Input OK");
}
var counter = 0;
while (counter < 10) {
counter++;
if (userInput == randomNum) {
alert("You win!");
}
if (userInput > randomNum) {
document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + " Guess lower! < br / > ";
alert("You have " + counter + " guesses left.");
} else if (userInput < randomNum) {
document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + "Guess higher! < br / > ";
alert("You have " + counter + " guesses left.");
}
break;
} // end while loop
} // end function myFunction()

This line
var counter = 0;
resets counter to 0 every time the function is called. One fix could be to set this as a global variable in this way
counter = 0; // note no var keyword
function myFunction() {...}
Then your calls to counter in the function will reference the global variable.
In addition, your while loop doesn't make sense. It should be a simple if statement to see if counter >= 10. Think about this logic after counter variable is being set correctly.

Step through the logic in your while loop.
The counter variable incrementing in each loop will already cause your loop to exit.
Setting a "break" at the end of the while loop means that you are guaranteed to exit after the first

Only break your loop when you actually want to exit it. In your case, that would probably be when the user has guessed the number or is out of tries.
The break command immediately ends the loop. Have a look at the MDN docs for more info!

Related

Removing alert from code forces it to enter infinite loop

I have a piece of code that has a few window alert messages. It works fine. However, if I remove the alert statements, the program enters into an infinite loop. This is weird for me.
Can someone help me identify the problem with the code?
function countSwaps(arr) {
let notVisited = {}, swaps = 0;
for (let i = 0; i < arr.length; i++) {
notVisited[i] = true;
}
while (Object.keys(notVisited).length) {
alert("main pass");
let nextPos, currentPos = Object.keys(notVisited)[0];
while (arr[currentPos] !== parseInt(currentPos+1)) {
nextPos = arr[currentPos] - 1;
[arr[currentPos], arr[nextPos]] = [arr[nextPos], arr[currentPos]];
swaps+= 1;
alert("Swap " + arr[currentPos] + " and " + arr[nextPos] + "\n");
delete notVisited[nextPos];
}
delete notVisited[currentPos];
}
return swaps;
}
console.log(countSwaps([2,3,4,1,5]));
Well, it runs an infinite loop for me without the alerts as well.
It seems like the problem is the following expression: parseInt(currentPos+1)
The addition happens before the conversion from a string to a number, so for example:
currentPos = '4';
currentPos + 1 == '41';
parseInt(currentPos + 1) == 41
What you want is probably parseInt(currentPos) + 1. Now:
currentPos = '4';
parseInt(currentPos) + 1 == 5
With this the loop seems to quit and I get the result of 3 swaps out of it.
This is cause of infinite loop.
while (Object.keys(notVisited).length)
It should be something like
while (Object.keys(notVisited).length > 0)
That is a property, it will always return true

Need to remove +=

The program usually displays something like 1+3+5+=9 but i want to get rid of the + after 5. Please help me with this issue that I have right now at the moment.
var userNum = prompt("Pick a number and every odd number between 1 and that
number will be added");
var increase = 0;
var totalSum = 0;
var expression = "+";
document.write("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
increase by one
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){
} else {
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
document.write( 0+ "=" + totalSum);
You could put the + sign in front, and on the first iteration, don't add it:
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added");
var increase = 1,
totalSum = 0,
expression = "+",
str = "The sum of the odd numbers is: ";
while(increase < userNum) {
if(increase !== 1) { str += expression; }
str += increase;
totalSum += increase;
increase += 2;
}
document.write( str + "=" + totalSum );
Instead of creating the output while iterating, put your numbers into an array and simply .join("+") (MDN) the final array to create the string 1+3+5 for output at the end.
I leave the implementation for you as an exercise.
add values to array and join with + sign.
HTML:
<div class="sum">
</div>
JS:
var userNum=10;
var increase = 0;
var totalSum = 0;
var expression = "+";
$('.sum').text("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
//increase by one
var txt=[];
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){}
else{
txt.push(increase);
totalSum = totalSum + increase
}
}
$(".sum").text(txt.join("+") + "=" + totalSum);
https://jsfiddle.net/u5o9qb0c/
Try checking for the last iteration of the while loop like- (you can replace your while loop with the below one)
while(increase < userNum){
increase++
if(increase % 2 !== 0){
if(increase === userNum){
document.write(increase)
}else{
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
}
Hope this helps.
First and foremost, don't use document.write(). It has very limited use cases and more often than not will overwrite your existing document. Instead, set up an empty HTML element to use as an "output" area and then just write into that area.
Next, you get the extra + symbol because you are writing:
document.write(increase + expression);
and expression is hard-coded to the + symbol.
You'll need to only add that when another operand is added.
It should be like this:
/*
Place all of this code in "script" tags and place those tags
just before the closing body tag (</body>) so that this code won't run
until all of the HTML is parsed
*/
// Get a reference to the output element
var output = document.getElementById("output");
var endNum = prompt("Pick a number and every odd number between 1 and that number will be added");
// Since we know you want to start at 1, initialze the variable to 1
var increase = 1;
var totalSum = 0;
// This will hold the result that will be injected just once into the document
var result = "";
// while the increase is less than the userNum , the increase will increase by one
while(increase < endNum){
// Just check to see if we've already started writing the result
// and prepend the + sign if so.
if(result !== ""){
result += "+";
}
result += increase;
totalSum += increase;
// Just increment by 2 to stay with odd numbers
increase += 2;
}
output.innerHTML += result + "=" + totalSum;
<div id="output">
<h1>The sum of the odd numbers are:</h1>
</div>
What you're doing could be a lot more concise. See below.
Changed this increase variable to initialize to one, because that's always your first value according to the prompt.
Starting the expression as the leading text, because a) I want this printed before anything else, and b) I don't want the plus sign on the first iteration
Regarding the expression assignment in the loop, it's unnecessary to assign this every iteration as I have, it's more concise to just assign it than to check if I need to do it every time.
I move the increment of increase to later in the loop so that the value that gets printed is the what it is at the start of the loop. It's a matter of preference, but I would have had to initialize it to -1 if I wanted this to work with it incrementing before the document.write, which I don't like from the standpoint of conveying clear intent.
I also got rid of the semicolons for no reason at all other than that they weren't necessary. (Addendum: In the context of this discussion, I'm not prescribing making this change. It's my code style, but adding semicolons between the statements would have no relevant impact on the code snippet.)
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added")
var increase = 1
var totalSum = 0
var expression = 'the sum of the odd numbers are:'
while (increase <= userNum) {
document.write(expression + increase)
totalSum += increase
increase += 2
expression = '+'
}
document.write("=" + totalSum)

My Javascript prompt runs before function even if prompt is located after the function

I wrote a small practice program that shows the times table for a prompted number.
I want the table to be shown after the user is asked for which number. If the user enters a different than -1 number, I want to ask for another number.
The sequence that I'm looking for is prompt the user, show the table, prompt the user show the table ... Unfortunately the sequence in which my program works is prompt the user, prompt the user, prompt the user ... AND JUST AFTER THAT show the tables for each input.
Obviously the code is not written in that way.
// get number to show time table for
var aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
while(aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
aNumber = prompt("Enter the number for time table or -1 to stop the program", ""); // ask for another number. HERE IS THE PROBLEM - THIS LINE RUNS BEFORE THE PREVIOUS ONE!
}
document.write("stopped");
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
document.write(number + " * " + i + " = " + number*i + "<br />");
}
}
// get number to show time table for
var aNumber = null;
var div = document.getElementById("textDiv");
setTimeout(enterNumber, 0);
function enterNumber()
{
aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
if (aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
setTimeout(enterNumber, 0);
}
else
div.innerHTML += "stopped"
}
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
div.innerHTML += number + " * " + i + " = " + number*i + "<br />";
}
}
<div id="textDiv">
</div>
#Teemu is correct. And I admit, it's a bit sloppy, but this should work. Try to avoid using document.write as it can have unpredictable results. Instead try other methods of output

How do I use innerHTML inside a loop using JavaScript?

Here is the code and snippet:
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 0; i <= amount; i++) {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Hi, I'm a new to Javascript and I can't figure this out. How can I write into the div tag "content" using the loop to display values inside the div tag per loop?
Change to += instead of = and start the for loop with 1 unless you want to print out as loop 0, loop 1 and so on...
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 1; i <= amount; i++) {
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Your code looks basically correct but you need to understand the context in which a browser executes javascript. For a given computation (event), the browser usually executes all of that computation before it does any redraws of the actual page. What this means in your case is that only the last value of innerHTML will be used. One approach to this is to accumulate the entire innerHTML value before returning (I see IsabelHM just posted that). The second would be to use something like setTimeout to spread the computation out over multiple "sessions" - something like
var i = 0;
count = function() {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
i++;
if (i < amount) {
window.setTimeout(count, 100);
}
};
count();
Note - I haven't run that but the idea is there. I basically count at 100ms intervals.

Treating numbers as strings

I got bored and decided to make a script, but it isn't working. Instead of adding the numbers, it treats them as strings, ex. 0 + 42 + 0 + 17 would be 042017. Also, the while script goes on forever.
var money = 0;
var yn = false;
var bye = 0;
var add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
add = 0;
console.log(money);
while (money < 1000000001 || bye == 1) {
yn = window.confirm("Do you want more money?");
if (yn) {
add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
console.log(money);
} else {
console.log("Goodbye!");
bye = 1;
};
};
if (money > 999999999) {
console.log("You won the game with " + money + " dollars!");
};
When you do
parseFloat(add);
it converts add to a floating point value and returns it. Since you are ignoring it, add remains unchanged as a string. You might want to replace the new value in add, like this
add = parseFloat(add);
Also, you can just convert the result of window.prompt itself, like this
add = parseFloat(window.prompt(...));
Most likely the reason your while loop is going on forever is because of the bye variable. Your logic is broken.
If the user answers No to the prompt, bye will be set to 1 and never change back. The while loop will continue as long as bye is 1, so it will go on forever.
To fix this, you can use:
while (money < 1000000001 && bye !== 1) {
or
while (money < 1000000001 || bye === 0) {
However, to store an on/off flag, you should be using a boolean variable, not a number:
var bye = false;
// ....
while (money < 1000000001 && !bye) {
// ....
if (yn) {
// ....
} else {
// ....
bye = true;
}
}
Also note that you don't need (read: shouldn't use) a semicolon after if and while blocks.

Categories

Resources