Code platoon conditional statements problem set - javascript

Getting my coding learning path started and I've run across a hiccup. I'm trying to write a program that represents the below;
// Write a program that prints a message to the screen based on a users age and country.
// Feel free to change these variables or create new ones so you can test all cases.
const age = 20
const country = 'USA'
// if the user is younger than 16 print "You're not old enough to do anything yet."
// if the user is at least 16 but not yet 18 print "Be careful driving."
// if the user is 18 but not yet 21 and the user lives in the USA pring "Go Vote!"
// if the user is at least 18 but younger than 21 and lives outside of the US print "You can probably have some wine."
// In all other cases print "You're old enough to figure it out for yourself."
So far ive got this:
const age = 20
const country = "USA"
const otherCountry = "Other country"
console.log(age)
console.log(otherCountry)
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
else if (age >=16 && age <=18) {
console.log ("Be careful driving")
}
else if (age >=18 && age <=21 && country) {
console.log("Go Vote!")
}
else if (age >=18 && age <=21 && otherCountry){
console.log ("You can prbably have some wine")
}
else
{console.log ("You're old enough to figure it out")
}
I cant seem to figure out how to get the country to be expressed in the "else if" statement. Noobies got to start somewhere. Thanks in advance

You have a problem with your logic.
First of all not yet 18 probably means < 18 and not <= 18. (same for 21)
Second, once you are in your "Go vote" branch, you can never enter the "Wine" branch anymore, because once, one condition is hit in an if .. else if .. else no other conditions will be evaluated any more.
So, if you have a person between 18 and 21, you have to check the addtional condition (ie lives in USA or any other country) in that branch.
let age = 19;
let livesin = "USA";
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
//you don't need >=16 here, because as the first condition failed
//we alread know that age >= 16
else if (age < 18) {
console.log ("Be careful driving")
}
//you don't need >=18 here, because as the first and second condition failed
//we already know that age >= 18
else if (age <21) {
//for people between 18 and 21, check if they live in the USA or not
if (livesin === "USA") console.log("go vote");
else console.log("You can prbably have some wine")
}
else {
console.log ("You're old enough to figure it out")
}

Related

why does "Number" make the "else if" work here?

I have a task to play a little with if/else if.
i don't understand why, when I write my code like the example below, the "else if(age === 18)" part doesn't work. it shows up as "undefined". the other 2 work.
But, when i add (Number(age) at all of them, it works. Why is that? why can i use 2/3 without "Number", but i need it to use 3/3?
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
You need to convert the string to a number. The easiest way is to take an unary plus +.
With a number, you can check with a strict comparison Identity/strict equality operator === against a number, because you have at least the same type.
var age = +prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else {
alert("Powering On. Enjoy the ride!");
}
prompt returns a string, which cannot be strictly equal to the number 18 since the types are different. It would work, however, if you used loose equality (==).
The simplest way to convert it to a number would be to use the unary plus operator, which has much the same function as the Number function.
var age = +prompt("Please type your age!");
It is because prompt returns a string.
The operators < and > will allow you to compare a string to a number, by pre-converting the string to a number and then comparing them. Read this article for more info on this, called "Type Coersion" in JS.
The === operator however will not do this type coercion/conversion, it will directly compare "18" with 18 and return false.
To fix this, you can instead use the other equals operator, ==, which does include type coercion.
However, a better way of doing it would be to check the input is definitely a number, like this:
var age = Number(prompt("Please type your age!"));
if (Number.isNaN(age)) {
alert("Try again with a number");
} else if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
cause prompt returns a stirng.
But < & > operators converts string to a number
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === '18') {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}

Code in Javascript, using if, else and prompt.

I am trying to write a code to answer the following. I have options of prizes. To be eligible for the prizes, you need to be within the age range of 20 and 40. If you are not eligible an alert saying you are not eligible will appear. If you are eligible; prompt will ask you for which prize you want and you need to answer with a numeric value. After they answer they will receive an alert that says "You will receive (prize, collected from the array) in your post within 2 weeks."
I have gotten this far with my code:
var prize = [
"0 = iPhone",
"1 = iPad",
"2 = iMac",
"3 = iPod"
];
var age = prompt("Please enter your age");
if (20 >= age && age <= 40){
alert("Sorry, you are not eligible for a prize.");
} else {
prompt("Which prize would you like to receive?");
} else if {
Would someone want to give me a hand? Thanks :)
You have mixed up a lot of the logic there, and actually put the "success" code within the "failure" condition.
I have no idea what you intend to do with the second prompt to choose the prize - and have even less clue why someone's age is the limiting factor in being eligible for a prize - but here is some logic that will correctly filter your desired age range:
var age = prompt("Please enter your age");
if (age >= 20 && age <= 40){
// handle successful prize claim here
}
else {
alert("Sorry, you are not eligible for a prize.");
}

CodeWars challenge. Which test is causing the fail?

Can anyone find out what is wrong with this code? I run the code on CodeWars and pass every test except one... sadly it does not display what the input was for that specific test so it is very difficult to figure it out.
Here are the challenge instructions:
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. A "Avengers" ticket costs 25 dollars.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
Return YES, if Vasya can sell a ticket to each person and give the change. Otherwise return NO.
I found that the code works for ALL tests if I swap the check for amount50 >= 1 and amount25 >= 1 with the amount25 >= 3 but I am not sure WHY this works.
function tickets(peopleInLine){
let amount25 = 0;
let amount50 = 0;
let amount100 = 0;
for(let i = 0; i < peopleInLine.length; i++){
if(peopleInLine[i] === 100){
if(amount25 >= 3){
amount25 -= 3;
amount100++;
}else if(amount25 >= 1 && amount50 >= 1){
amount25 -= 1;
amount50 -= 1;
amount100++;
}else{
return "NO";
}
}
if(peopleInLine[i] === 50){
if(amount25 >= 1){
amount25--;
amount50++;
} else {
return "NO";
}
}
if(peopleInLine[i] === 25){
amount25++;
}
}
return "YES";
}
On Codewars you can put console.log statements (or equivalent statements in languages other than JavaScript) in your code to print the input parameters or other variables when you're having trouble figuring out what is going wrong in your code or with your assumptions about the input. I just did this with your code and saw that the test your code is failing on is [ 25, 25, 25, 25, 50, 100, 50 ], so that should show you exactly why your code would be failing when in response to getting a $100 you first try to return three $25s as change instead of checking for a $50 and $25 first -- you receive four $25s, one of which you give as change to the first person with a $50, but then because you give the remaining three $25s (rather than the $50 and one $25) as change to the person with the $100, you no longer have a $25 to make change for the last person's $50.

else statement within nested if statements. How does this code know which else statement to execute?

I get the nested if loops (same as using && operator), but how does this code here know which conditions to execute with no conditions and just back to back else statements? One of them is within the nested if statements. I can tell that's obviously why this works the way it does, I just don't get how. Also, I know how to write this in several more readable ways testing multiple conditions. Please just explain what is happening with this code here. How does it know to output "You are too old" or "You are too young?"
var age = prompt("Please enter Your age here :");
var min_age=18;
var max_age=40;
if(age>=min_age){
if(age<=max_age){
console.log("You meet the requirements for this competition");
}else{
console.log("You are too old");
}
}else{
console.log("You are too young");
}
The if-then-else ambiguity is known for a long time. All languages have solved it by defining that an else will match the first perceding if. So:
if (a)
if (b)
x = 1;
else
x = 2;
resolves to:
if (a) {
if (b) {
x = 1;
}
else {
x = 2;
}
}
EDIT by Nisar's reuest:
The if statement is defined as:
if (<condition>) <statement> [else <statement>]
This means that a <statement> in the above may also be an if statement. So, for example:
if (<condition>) if (<condition>) [else <statement>] [else <statement>]
As each else part is optional, the compiler has no way of knowing when it sees an else part to which if it belongs. To solve that the language defines that an else always matches the first preceding if.
The brackets {} set the limit.
Try to think in pseudocode, look beyond the characters and think about what is happening.
Reading in order:
If you are old enough
If your are not too old
'You meet the requirements for this competition'
OTHERWISE
'You are too old'
END
OTHERWISE
'You are too young'
END
Note how indentation can help see the limits of the conditions. Each indented part can be separated.
Firstly, let's indent your code.
var age = prompt("Please enter Your age here :");
var min_age = 18;
var max_age = 40;
if (age >= min_age)
{
if (age <= max_age)
{
console.log("You meet the requirements for this competition");
}
else
{
console.log("You are too old");
}
}
else
{
console.log("You are too young");
}
Starting off..
var age = prompt("Please enter Your age here :");
Let's say you enter 21 in the prompt box, so age=21
We initialize
var min_age = 18;
var max_age = 40;
Now let's look at the first if condition.
if (age >= min_age)
If you substitute the values,this translates to
if (21 >= 18)
This is true,therefore we go inside the if block and not to the else.
The next line is.
if (age <= max_age)
This translates to
if (21 <= 40)
Considering this is also true, we print You meet the requirements for this competition.
The most important take-away from this is, indent your code, and the rest becomes pretty simple.
There are just 3 Options
too young
correct age
too old
First Check - is the person old enough?
if(age>=min_age)
Second check - is the person too old?
if(age<=max_age)
the only possible option left after this if statment is FALSE :
too old

I need someone to look over some javascript code for me because I'm getting an error that says syntax error

I need someone to look at this code. I am a beginner at javascript and I can't find the error(s) in this code I made.
var user = prompt ("Are you a goblin, knight, troll, human, or wizard?").toLowerCase()
var name = prompt("What is your name?").toLowerCase()
var gender = prompt("Are you male or female?").toLowerCase()
switch(user) {
case 'goblin':
console.log("Hello, you are going to have a fun journey as a goblin");
var meetAnt = prompt ("You run into a giant ant eater, you can attack or run. Do you choose to attack?").toLowerCase()
if(meetAnt = yes) {
console.log ("you stab him in the eye, but then he hits you with his trunk. You are injured");
var finishAnt = prompt("you can either risk your life and finish him, or try to run away. Do you finish him?").toLowerCase()
if(finishAnt = yes) {
return true;
console.log("congratulations you have killed the aint eater!")
}
else if(finishAnt = no) {
return false;
console.log("You run away and barley make it, you are badly hurt");
else {
console.log("sorry thats not an option")
}
}
}
else {
return true;
console.log("You run past the ant eater and get to saftey. You are very lucky")
}
break;
case 'knight':
console.log("Hello, you are going to have a fun journey as a knight");
var dayFight = prompt("You are versing the goblins in a fight, you need to choose how many days you go to fight(1-100). Remember if you choose too little days then you won't have stayed long enough to win the fight but if you stay to long you have more of a chance of dying or getting injured").toLowerCase()
if(dayFight < 40) {
return false;
console.log("You did not fight enough days, which has resulted in your kingdome loosing the war to the goblins.");
}
else if(dayFight > 60) {
return false;
console.log("You have went to war to long and been seriously injured.");
}
else if(40<=dayFight=>60) {
return true;
console.log("You have been at war for the right amount of time. You have came out of the war with no injuries and you also have defieted the goblins!")
}
break;
case 'troll':
console.log("Hello, you are going to have a fun journey as a troll");
var red = true;
var green = true;
var yellow = false;
var blue = false;
var houseRaid = prompt("You see four huts in the middle of the woods. You can raid two. There is a red hut, blue hut, yellow hut, and green hut. What is one color house that you want to raid?").toLowerCase()
var doorPick = prompt("Do you want to enter throuhg the back door or front door?").toLowerCase()
if(doorPick||houseRaid = "red"||"green" && "back door") {
return true;
console.log("You raided these houses and left before any villagers would see you");
}
else {
return false;
console.log("You raided those houses, but one of them was a booby trap and you are now captured");
}
break;
case 'human':
console.log("Hello, you are going to have a fun journey as a human");
var reinforceFound = prompt("You know a storm is comming and you have to reinforce your hut, but you only have enough material to reinforce either your lower foundations or higher foundations. Which do you inforce? Higher or lower?").toLowerCase()
if(reinforceFound = lower) {
return false;
console.log("The storms winds pushed down the top of your house and caved in your roof.");
}
else if(reinforceFound = higher) {
return true;
console.log("The storm did not do that much damage to your house due to your reinforced higher foundations. Good choice");
}
else {
console.log("sorry but that is not an option. Pick either 'higher', or 'lower'")
}
break;
case 'wizard':
console.log("Hello, you are going to have a fun journey as a wizard");
var blood = true;
var dust = true;
var wings = false;
var mushrooms = false;
var postion = prompt("You are working on a new healing potion but you do not know what you need to add to finish it. You have 4 ingrediants; blood, dust, wings, mushrooms. Pick one too add. (WARNING: Pick carefully because if you choose the wrong ingerdiant, then your potion will be ruined.)").toLowerCase()
if(postion = wings || mushroom) {
console.log("You picked a bad ingrediant and now your potion is ruined.");
}
else if(postion = dust || blood) {
console.log("you picked the right ingrediant and your potion is okay")
}
else {
console.log("sorry but that is not an option");
}
break;
default:
console.log("Sorry but that is not a character in the game");
};
I am making this code for a lesson in the website www.codecademy.com. It is supposed to be a small part of a game. Sorry there is so much, I couldn't narrow down anymore were the error is coming from.
The syntax error is because you are missing an ending bracket at line 18 (of the posted code). This:
else {
should be:
} else {
The missing bracket means that there is no matching if before the else.
Some other problems in the code, but perhaps not all of them:
You are missing semicolons at the end of many statements. They are not required when the statement ends where the line ends, but they are recommended.
You have a problems with comparisons like these:
if(meetAnt = yes) {
The comparison operator is == (or ===), and you are missing delimiters around the string value, so it would be interpreted as a variable name. It should be:
if(meetAnt == "yes") {
In comparisons like these you get unexpected results:
if(dayFight < 40) {
The variable contains a string, so the value 40 is converted to the string "40" for the comparison, and they are compared as strings instead of numbers. That means that for example "100" < "40". You should parse the input string to a number:
dayFight = parseInt(dayFight, 10);
With comparisons like this the syntax is wrong:
else if(40<=dayFight=>60) {
Comparing one value using two operators doesn't work, and there is no => operator. You need two conditions:
else if(40 <= dayFight && dayFight <= 60) {
In comparisons like this you have used the || operator wrong (and the wrong comparison operator and the missing string delimiters):
if(postion = wings || mushroom) {
It's used between conditions, not to compare multiple values in one condition:
if(postion == "wings" || postion == "mushroom") {
When you put a statement after return, that statement will not be executed as the code exits the function at the return statement:
return true;
console.log("congratulations you have killed the aint eater!")
Reorder them:
console.log("congratulations you have killed the aint eater!")
return true;

Categories