JavaScript 99Bottles - Infinite Loop - javascript

(I already know that this isn't the most elegant solution to the 99 bottles code challenge, but I'd really like to know how not to repeat this mistake in the future.)
When this runs in the console it repeats the (count === 0) condition and repeats nothing but the "0 bottles of beer" console log until it crashes.
I've experimented with using a 'break' statement after the count decrements to 0, but haven't had any success.
let count = 99;
function bottlesOfBeer() {
while (count >= 0) {
if (count > 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
count--;
console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");
};
if (count === 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
} //*this is where I tried the break statement*
}
};
bottlesOfBeer();

You only decrement count when it is above 0, so it never goes below 0; but the loop continues as long as count >= 0.

Here's the corrected code:
function bottlesOfBeer() {
var count = 99;
while (count > 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
count--;
console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");
}
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
};
bottlesOfBeer();
Please read and understand - and ask, if you have questions.
In the code, count was set to 99.
The while loop stops when count gets to zero.
When the loop exists, count IS zero, and the appropriate line of the song is logged.
I've removed blank lines...
Other than that - your code is pretty neat: no weird indentations (you wouldn't believe what I see - not that it would effect execution, just easier to read).

Turn while (count >= 0) into while (count > 0) and you are good to go!
The problem is that when it reaches zero you just log the message without decreasing it any more, so it stays zero and (count >= 0) is always true.

Related

I am trying to get a JavaScript Program to Print a letter grade and Percentage based on a average using a switch statement but the answer comes up NaN

In my program I am using a do-while loop to prompt for grades until a -1 is entered and then increments the amount of grades inputted. A while loop then checks if the grade isNaN or less then 0 or greater then 100. The program will ask for another grade if so. If a -1 is entered the program will break from the loop and calculate the average based on the counter for the grades and the total number of grades added together. When I run the program and put in a negative 1 to stop it prints the -1 inside of the table and the semester average displays as NaN. I am assuming this is because the negative -1 makes it not a non positive number but I am unsure how to fix this.
Here is my code.
do {
grade = prompt('Enter grade(-1 to stop)');
count++;
while (grade < -1 || grade > 100 || isNaN(grade)) {
grade = prompt('Enter grade again (-1 to stop)');
}
document.write('<td>Grade ' + count + '</td>');
document.write('<td width="50"> ' + grade + ' </td>');
document.write('</tr>');
}
while (grade != -1) {
--total;
alert("You have input -1 to stop");
document.write('</table>');
}
total = total + grade;
avg = total / count;
document.write('Semester Average: ' + avg + '<br /><br />');
I tried to fix your problem here
https://jsfiddle.net/51v3qft9/26/
This is the snippet which may not be correct as your logic but it works for me
var count = 0
var total = 0
var avg = 0
document.write('<table>');
do {
grade = prompt('Enter grade(-1 to stop)');
//if user key-in nothing, we need to ask user to key-in again
while (!grade || grade < -1 || grade > 100 || isNaN(grade)) {
grade = prompt('Enter grade again (-1 to stop)');
}
//whenever user key-in -1, we need to break `while`
if (grade == -1) {
break
}
count++;
document.write('<td>Grade ' + count + '</td>');
document.write('<td width="50"> ' + grade + ' </td>');
document.write('</tr>');
total += Number(grade); // you need to convert `grade` to number
} while (grade != -1)
alert("You have input -1 to stop");
document.write('</table>');
if(count > 0) {
avg = total / count;
}
document.write('Semester Average: ' + avg + '<br /><br />');
Is this what you want?
https://jsfiddle.net/sean7777/qtf3v4rn/26/
Hope this helps :)

Undefined variable in part of the loop, output

I am a beginner in JS and I am wondering why the first loop result, outputs an "undefined" variable but the rest have the"bottles" included. It is meant to output a statement, from 99 to 1.
Here is a snippet of the code:
/*
* Programming Quiz: 99 Bottles of Juice (4-2)
*
* Use the following `while` loop to write out the song "99 bottles of juice".
* Log your lyrics to the console.
*
* Note
* - Each line of the lyrics needs to be logged to the same line.
* - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
*/
var num = 99;
let statementSplit = ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
// var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);
The bottles is not encased in double quotes in your let statementSplit... line the very first time that you call it. Instead, it should be
let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));
Try with the edited snippet. The bottles should be added as a string and not as a variable when it is declared in the beginning.
/*
* Programming Quiz: 99 Bottles of Juice (4-2)
*
* Use the following `while` loop to write out the song "99 bottles of juice".
* Log your lyrics to the console.
*
* Note
* - Each line of the lyrics needs to be logged to the same line.
* - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
*/
var num = 99;
let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
// var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);
As stated by other you indeed have an undefined variable in the first statementSplit assignment.
I would move the first statementSplit assignment inside the while loop as well, as to increase maintainability (in case you need to change the lyrics in the future):
var num = 99;
let statementSplit = "";
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);
Replace "let" with "var" , with var java script allow "hoisting" ...

My code isn't recognizing a condition

I am trying to solve this following problem (Udacity's Intro to Javascript):
Directions:
Write a loop that prints out the following song. Starting at 99, and ending at 1 bottle.
Example:
99 bottles of juice on the wall! 99 bottles of juice! Take one down, pass it around... 98 bottles of juice on the wall!
98 bottles of juice on the wall! 98 bottles of juice! Take one down, pass it
around... 97 bottles of juice on the wall!
...
2 bottles of juice on the wall! 2 bottles of juice! Take one down, pass it around... 1 bottle of juice on the wall!
1 bottle of juice on the wall! 1 bottle of juice! Take one down, pass it around... 0 bottles of juice on the wall!
and my code doesn't appropriately output the last line (it doesn't include "s" after "bottle"):
My code looks like this:
var num = 99;
while (num >= 1) {
num == 1 ? ((plural = "") && (nextPlural = "s")) :
num == 2 ? ((plural = "s") && (nextPlural = "")) :
((plural = "s") && (nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + "bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
why is this code ignoring my condition for "num == 2?" at the last line of output?
FYI, I was able to solve this using the following code, but it didn't look clean so I wanted to optimize this:
var num = 99;
var plural = "s";
var nextNum = num - 1;
var nextPlural = "s";
while (num >= 1) {
if (num > 1 && nextNum > 1){
plural = "s";
nextPlural = "s";
}
else if (num > 1 && nextNum == 1){
plural = "s";
nextPlural = "";
}
else if (num == 1 && nextNum <= 1){
plural = "";
nextPlural = "s";
}
console.log(num + " bottle" + plural + " of juice on the wall! " + num + " bottle"+ plural + " of juice! " +
"Take one down, pass it around... " + nextNum + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1;
nextNum = num - 1;
}
Alright, so the question, if I understand it right, is why the last line for the first code sample outputs "0 bottle" instead of "0 bottles".
So let's translate what you attempted to achieve with your code into English and figure out what the interpreter does:
Set num to 99.
While num greater or equal to 1, do the following:
2.1 If num equals 1, set plural to "" and nextPlural to "s".
2.2 Else if num equals 2, set plural to "s" and nextPlural to "".
2.3 Else set both plural and nextPlural to "s".
The console output is trivial, so I won't mention it here.
Set num equal to num-1.
You might notice that substituting the ternary operator with an if statement yields the correct result:
var num = 1;
var plural = '';
var nextPlural = '';
while (num >= 1) {
if(num==1) { plural = ''; nextPlural='s'; }
/*num == 1 ? ((plural = "") && (nextPlural = "s")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));*/
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
What does that mean? That there is a syntax error with your use of the ternary operator. What could it possibly be? Let's declare a new variable and try setting and outputting it along with the others.
var num = 1;
var plural = '';
var nextPlural = '';
var test = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? ((plural = "") && (nextPlural = "s") && (test = "test")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
console.log(test);
num = num - 1
}
You will notice that test remains equal to an empty string, just like nextPlural. That's because using && is not the correct way of instantiating variables inside ternary constructions, so this code will work as intended:
var num = 99;
var plural = '';
var nextPlural = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? (plural = "", nextPlural = "s") : (num == 2 ? (plural = "s", nextPlural = "") : (plural = "s", nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
--num;
}
If you are interested, this is how I would probably program the solution:
for(var i=99, w=' on the wall!'; i>0; i--) {
console.log(returnEmpties(i)+w+' '+returnEmpties(i)+'! Take one down, pass it around... '+returnEmpties(i-1)+w);
}
function returnEmpties(n) { return n+' bottle'+(n==1?'':'s')+' of juice'; }
The ternary operator stuff is just a big mess, I've tried to figure it out, but it's really worth trying to fix since it's just not a good idea to use ternary operators like that. You've nested a ternary inside another ternary and basically have an if, else if, else condensed into 3 lines.
You can avoid doing extra logic and realize that you need only add an 's' when the number is not 1.
By extracting this logic into a function that returns the string 's' or the empty string '', you can simply plug this function into your loop and provide it with n and n-1.
function plural(n) {
return n == 1 ? '' : 's'; // note this is the appropriate usage of a ternary operator
}
You can then simply your loop to just
while (num >= 1) {
console.log('...'); // left as an exercise for you to fill in the required function call and string concatenations.
num--; // same thing as num = num - 1;
}

jQuery if less than 10 do this, else if 0 do this not working

I'm rather new to JavaScript and I'm having a little problem with this if/then/else if statement. I tried a few things below but am stuck. Does anyone have any ideas?
if (variant.inventory_management == "shopify" && variant.inventory_policy != "continue") {
if (variant.inventory_quantity < 10) {
$lowStockAmount.html('Last few remaining! only ' + variant.inventory_quantity + ' left');
} else if (variant.inventory_quantity < 1) {
$lowStockAmount.html("We're sold out, Don't worry! <a href='#'>click here</a> to be notified when it's back in stock.");
}
}
I tried == 0 as well but I end up with the same thing: it just shows the last few remaining! only 0 left but if it is 0, I'd like it to show the sold out message.
Here is a simplified answer to your problem. If the quantity is 0, show the "We're sold out" info. Else, if the quantity is not 0 but less than 10, show the "Last few remaining" info. Otherwise don't show anything.
var quantity = 10;
if (quantity === 0) {
console.log("We're sold out, Don't worry! <a href='#'>click here</a> to be notified when it's back in stock.");
} else if (quantity < 10) {
console.log('Last few remaining! only ' + quantity + ' left');
}
The quantity == "0" will not work, because you're comparing a number with a string.
EDIT: quantity == "0" will work but is not a proper style of comparing two values.
Think about the logic as it is right now. If variant.inventory_quantity is 0, the "else if" statement will never run, because it will only be checked if variant.inventory_quantity is NOT less than 10.
Here's the fix. Change this line:
if (variant.inventory_quantity < 10) {
to this:
if (variant.inventory_quantity < 10 && variant.inventory_quantity > 0) {

Javascript number guessing game

I can't seem to make this code alert the user when the correct answer is found, nor can I make the pop-ups continue to loop to play again. I coded this as a learning exercise. In JS i'm very noob.
Can someone review my code and offer constructive criticism?
// noprotect
var targetNumber = Math.floor(Math.random() * 100 + 1);
var userGuess = prompt("Pick a number from 1 to 100 to guess which one I'm thinking about!" + " (6 guesses left.)");
for (var i=5; i>0; i--) {
if (i === 0) {
prompt("Out of guesses!" + " (" + i + " guesses left.)" + " My number was: " + targetNumber);
}
if (isNaN(userGuess) === true) {
userGuess = prompt("That value was not a number! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess < 1 || userGuess > 100) {
userGuess = prompt("That number was not between 1 and 100 inclusive! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess === targetNumber) {
userGuess = alert("You're correct! My number was: " + targetNumber);
}
if (userGuess < targetNumber) {
userGuess = prompt("You're too low, guess again" + " (" + i + " guesses left.)");
}
if (userGuess > targetNumber) {
userGuess = prompt("You're too high, guess again!" + " (" + i + " guesses left.)");
}
}
You're comparing the string value prompt() returns with a number using ===. That's not going to work.
Instead:
var userGuess = parseInt(prompt(...))
It's worth noting that prompt is an extremely clunky way to do this. What would be better is creating a form where you have a proper <input> field and a place to put the responses.
Just to add a quick note before I head home from the office. Your for loop will never allow i === 0condition to pass because the loop only continues if i > 0. You likely want to change this to i >= 0 or adjust your conditions within the loop.

Categories

Resources