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.");
}
Related
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")
}
Hey i am working on a guessing game project with javascript that entails inputing a number into a prompt "Give me a number between 1 and 10." Instructions are to incorporate the following:
while the guess is not equal to the target
Prompt for a new guess
If the guess is less than the target
print "too low!"
else If the guess is greater than the target
print "too high!"
else
print "You got it!"
So I have my while loop and if conditional statements but i don't know how to contain my if statements inside my while loop. My actual results just prompts me to Guess again repeatedly without alerting too high! or too low! My else statement when guessing the right number seems to work though. Thank you.
let min = 1;
let max = 10;
let target = Math.random() * (max - min + 1);
target = Math.floor(target) + min;
let guess = (0);
guess = prompt("Give me a number between 1 and 10");
console.log("Your guess is" + guess);
while (guess != target) {
prompt("Guess again");
console.log(guess);
}
if (guess < target) {
alert("too low!");
console.log("too low guess", guess);
} else if (guess > target) {
alert("too high!");
console.log("too high guess", guess);
} else {
alert("You got it!");
}
Your code is currently doing this:
Forever: ask "guess again"
After 'forever' is over (which is never!) check the value of guess. Furthermore, the value of guess is the same as the first time the question as asked.
You'll want this:
Forever: ask "guess again"
After "guess again", check and store the stored value of the last answer.
If the answer is correct stop the forever running loop.
But what is also important: make sure prompt returns a number, because anything could be entered in a text prompt.
So that would be:
// See Note 1.
guess = parseInt(prompt("Give me a number between 1 and 10"), 10);
console.log("Your guess is" + guess);
// 1. Do something forever
while (guess != target){
// 2. store the last answer
guess = parseInt(prompt("Guess again"), 10);
console.log(guess);
// 2b. check the last answer
if (guess < target){
alert("too low!");
console.log("too low guess", guess);
}else if (guess > target){
alert("too high!");
console.log("too high guess", guess);
}
// 3. If the answer is correct, `guess === target` so the loop will end.
}
// See Note 2.
alert("You got it!");
Note 1: If the player enters something that can't be turned into an integer, parseInt(, 10) will return NaN (not a number). You can test that: isNaN(123) / isNaN(NaN).
Note 2: Your application will not show a message if the player gets it correct in one go, because "you got it" was inside the loop. If the answer was right the first time, the loop would never be entered. Put the message outside the loop to fix that.
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.
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'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.
prompt will always return a string so in your case:
var integerAge = parseInt(age);
if(!isNaN(integerAge) && age === '' + integerAge)
alert("data is integer")
else
alert("data is not an integer")
In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0 or custom minimum and maximum in the next validation step.
Prompts always return strings, but since JS is loosely typed language, those Strings will get autocasted into Numbers when needed (Integers are called Numbers in JS), which is why your example works fine.
For a better check, you can use !isNaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
alert(!isNaN('10'));
alert(!isNaN('abc'));
alert(!isNaN(10));
For the lunatic downvoters, here's an optimized version of OP's code:
var age = parseInt(prompt("Please enter your age", "Enter age"), 10);
alert(isNaN(age) ? 'Not a number' : age);
You can try this one to check if its an integer:
function isInteger(x) {
return x % 1 === 0;
}