My code isn't recognizing a condition - javascript

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;
}

Related

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" ...

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

Absence and presence of curly brace in "if" statement

var i = 0,
j = 8;
checkiandj: while (i < 4) {
console.log("i: " + i);
i += 1; // i=1;
checkj: while (j > 4) { //j=8
console.log("j: "+ j);
j -= 1; // 7
if ((j % 2) == 0)
continue checkj;
console.log(j + " is odd.");
}
console.log("i = " + i);
console.log("j = " + j);
}
How does this part of the code works?
if ((j % 2) == 0)
continue checkj;
console.log(j + " is odd.");
Is it like this?
if ((j % 2) == 0)
continue checkj;
else
console.log(j + " is odd.");
or like this?
if ((j % 2) == 0) {
continue checkj;
}
console.log(j + " is odd.");
And if I will read this statement(original one) at first look, I will understand it as: if Divide modulo 2 equal zero , do both continue checkj and console.log, not only continue. I know that what makes "continue" , but it`s hard to understand this action without curly braces. How can I understand better absence of curly braces?

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.

Dice Game - need to roll more dice based upon circumstances

I am developing a game idea. Weapons can be equipped on your character. Different weapons have different amounts of damage dice and critical hit dice. I have it working currently so that the program rolls the appropriate amount of dice based on your equipped weapon.
However, the program only rolls one critical dice, despite whether the equipped weapon contains two critical roll dies.
var WepEquipped = { "name": "Broken Sword", "attack_dice": "2", "critical_dice": "1", "min_base_dmg": "2", "max_base_dmg": "12", "max_total_dmg": "24", "weapon_type": "Slash" };
function Attack(rolls) {
var total = 0;
var dice = [];
for (var i = 1; i <= rolls; i++) {
var d6 = Math.floor((Math.random() * 6) + 1);
$("#dice_container").append("<div class='die_roll'><p class='atk-roll'>" + d6 + "</p></div>");
dice.push(d6);
total += d6;
}
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
$('#attack_button').off('click').on('click', function(){
$('.die_roll').hide();
Attack(WepEquipped.attack_dice);
// Attack(WepEquipped.attack_dice);
});
I can explain much more, but I hope this is enough code to grasp what I'm asking. Something here needs to change but I cannot figure out what:
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
your grep returns the number of elements in the dice array that equal to your first roll and if the length of that array equals the number of rolls that were made you roll the critical dice once.
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
If you're trying to roll as many times as the grep returns you need something like this.
var crits = $.grep(dice, function (elem) {return elem === dice[0];});
if( crits.length == rolls ){
for( var x=0;x<crits.length;x++){
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
}
Sorry for the double post, was on an abandoned account.

Categories

Resources