Error in if statement for setting balance - javascript

Am getting an if statement error, but can't figure it out. Can you tell me what's wrong?
var balance = 20.97;
if (balance < 10.00 ) {
// console.log() the balance minus 5 dollars
console.log("Your balance is (balance - 5.00).");
} else {
// Just console.log() the balance
console.log("Your balance is (balance).");
}

You're just printing a string. Placeholdering works like this:
console.log('Your balance is %s.', balance - 5.0);

console.log("Your balance is (balance - 5.00).");
should be
console.log("Your balance is %s.", (balance - 5.00));
The former will just say "Your balance is (balance - 5.00)" because JavaScript does not treat words like "balance" as variable references when they appear inside a string literal.
In the second, the message format string is distinct from the expression you want to display, and console.log replaces %s sequences with the other arguments.

Related

Functions in javascript - beginner question

Kia ora,
I'm am working on a problem that requires a function and array to be used in the answer. I'm a beginner!! The program needs to ask the user for a number between 1 and 30 that will get translated to either French or German. I've got it all working without using a function. I guess this is a little bit backwards, but now I need to get the function into the code. My understanding of them is beginner level, and there is something that I am missing despite watching countless videos. I'll attach what I have done with comments through it about my thinking. Thanks in advance for your help.
//write function to translate number into choosne language
function translate(number,lang){
//let phrase worked when I had it at the bottom of all the code, ie when there was no function!
let word = lang === "french"? french[number] : german[number];
//relates to function. I think I need tohave the above line return a value, this is what I
think this shold look like
return translatedNumber;
}
//array for French numbers 0-30
let french = ["zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf",
"dix", "onze", "douze", "treize", "quatorze", "quinze", "seize", "dix-sept", "dix-huit", "dix-
neuf", "vingt", "vingt et un", "vingt-deux", "vingt-trois", "vingt-quatre", "vingt-cinq",
"vingt-six", "vingt-sept,", "vingt-huit", "vingt-neuf", "trente"];
//array for German numbers 0-30
let german = ["null", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht",
"neun", "zehn", "elf", "zwölf", "dreizehn", "vierzehn", "fünfzehn", "sechszehn", "siebzehn",
"achtzehn", "neunzehn", "zwanzig", "einundzwanzig", "zweiundzwanzig", "dreiundzwanzig",
"vierundzwanzig", "fünfundzwanzig", "sechsundzwanzig", "siebenundzwanzig", "achtundzwanzig",
"neunundzwanzig", "dreiβig"];
//this block asks for number, gives message if number given is outside scoop. Started with if statement and got forever loop when answer was outside scoop. Changed to while and it works.
let number = prompt ("What number to translate? ");
while (number <= 0 || number > 30) {
alert ("Enter a number between 1 and 30.");
number = prompt ("What number to translate? ");
}
//while statement to ask tranlate langugae wanted. changes answer to lowercase so comparision works regardless of case that the user inputs.
let lang = prompt ("What language to translate? ");
while (lang.toLowerCase() !== "french" && lang.toLowerCase() !== "german") {
alert ("Enter french or german only");
lang = prompt ("What language to translate? ")
}
//I was thinking this would take the answer from the function and then use it in the alert to answer the users question.
let translatedNumber = translate(number, lang);
alert ("The number " + number + " is " + word + " in " + lang);
Easy! just wrap it in a function and call that function!
cut this code into translate()
//array for French numbers 0-30
let french = ["zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf",
"dix", "onze", "douze", "treize", "quatorze", "quinze", "seize", "dix-sept", "dix-huit", "dix-
neuf", "vingt", "vingt et un", "vingt-deux", "vingt-trois", "vingt-quatre", "vingt-cinq",
"vingt-six", "vingt-sept,", "vingt-huit", "vingt-neuf", "trente"];
//array for German numbers 0-30
let german = ["null", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht",
"neun", "zehn", "elf", "zwölf", "dreizehn", "vierzehn", "fünfzehn", "sechszehn", "siebzehn",
"achtzehn", "neunzehn", "zwanzig", "einundzwanzig", "zweiundzwanzig", "dreiundzwanzig",
"vierundzwanzig", "fünfundzwanzig", "sechsundzwanzig", "siebenundzwanzig", "achtundzwanzig",
"neunundzwanzig", "dreiβig"];
it belongs in that method, not outside of it.
finally put this last bit of code in its own method :
function startMethod(){
//this block asks for number, gives message if number given is outside scoop. Started with if statement and got forever loop when answer was outside scoop. Changed to while and it works.
let number = prompt ("What number to translate? ");
while (number <= 0 || number > 30) {
alert ("Enter a number between 1 and 30.");
number = prompt ("What number to translate? ");
}
//while statement to ask tranlate langugae wanted. changes answer to lowercase so comparision works regardless of case that the user inputs.
let lang = prompt ("What language to translate? ");
while (lang.toLowerCase() !== "french" && lang.toLowerCase() !== "german") {
alert ("Enter french or german only");
lang = prompt ("What language to translate? ")
}
//I was thinking this would take the answer from the function and then use it in the alert to answer the users question.
let translatedNumber = translate(number, lang);
alert ("The number " + number + " is " + word + " in " + lang);
}
then at the end, call your function!
startFunction();

how to detect mobile numbers in a string using javascript

To be honest, this sound like a duplicate post, but this is totally different from other post.
I'm building a chat room, where i would like to detect mobile number in user sending messages and warn the users that sending mobile numbers in the chat room is not safe and its against our policy.
There are few posts shows how to detect US number. But what about Indian numbers? they are 10 digit numbers.
var input = "hey im emily, call me now 9876543210"
I have to detect the number in all these formats.
9876543210
9 8 7 6 5 4 3 2 1 0
98765 43210
+919876543210
+91 9876543210
Some smart users always comes up with a smart way to come around those filters used in the client side javascript. So i have to be well prepared to detect all the method they use.
Example Message :
"hey this is emy, call me now 9876543210"
Expected output : pop up saying, hey buddy, sending numbers in the room is not safe and not allowed here.
Note: The string message should be allowed to send upoto 5 digit numbers, without getting the alert pop up. Or if you have any better idea? suggest me and we can make it work. Thanks
Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
Although you need to add conditions for special numbers like 911, 100, 101
In your test cases the length of phone number is 10:
So try the following code:
let input = "hey im emily, call me now 9 876543210";
let matched = input.match(/\d+/g).join('');
let phoneNumberLength = 10;
if (matched.length >= phoneNumberLength) {
console.log(`we've found a phone number. The number is ${matched}`);
} else
console.log(`The message does not contain phone number`);
Try to adjust this code as it is desired
UPDATE:
This code is intended to get desired results with test case by #tibetty:
let input = 'hi dude, please call my cell phone +86 13601108486 at 300pm"'
let matched = input.split(' ');
let maxIndex = matched.length - 1;
let filtered = matched.filter((s, i) => {
if (i != maxIndex && isNumeric(s) && isNumeric(matched[i + 1]))
return true;
if (isNumeric(s))
return true;
return false;
});
console.log(` The number is found ${filtered.join(' ')}`);
function isNumeric(n) {
return n.match(/^(?:[+\d].*\d|\d)$/);
}
try this one:
https://www.w3resource.com/javascript/form/phone-no-validation.php
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

issues with this program

I came across this program from a You Don't Know JS books book on github:
const SPENDING_THRESHOLD = 200;
const TAX_RATE = 0.08;
const PHONE_PRICE = 99.99;
const ACCESSORY_PRICE = 9.99;
var bank_balance = 303.91;
var amount = 0;
function calculateTax(amount) {
return amount * TAX_RATE;
}
function formatAmount(amount) {
return "$" + amount.toFixed( 2 );
}
// keep buying phones while you still have money
while (amount < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE;
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
// don't forget to pay the government, too
amount = amount + calculateTax( amount );
console.log(
"Your purchase: " + formatAmount( amount )
);
// Your purchase: $334.76
// can you actually afford this purchase?
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}
// You can't afford this purchase. :(
My issue is that it does not matter if I change the value of bank_balance to a higher value, but it keeps printing : You can't afford this purchase.
I have try to make it so it does not print : You can't afford this purchase.
I can't make it work. I'm starting to think that the program is wrong, but I think is just me.
I know the solution is simple but I cant see it nor find it.
It comes from your while(amount < bank_balance). You increase amount until it's bigger than bank_balance. So obviously, it's bigger than bank_balance after that.
Also, you can use the developer tools available in every modern browser (F12 for Chrome or Firefox will open them), where you can put break points and follow your code's flow.
I don't know what the program is meant to do but it doesn't seem to make much sense to me.
It "buys" phones as long as you have money, but doesn't check if you have enough money for an additional phone.
So in the end of the while loop you have spend exactly your whole money on phones or (much more likely) spend more money than you have.
On top of this there are accessorizes and taxes. So in the end, you won't ever be able to afford your purchase.
And no matter how high you raise you balance, the program is written to exceed it.
The programm would work probably better with the line
while (amount + PHONE_PRICE + calculateTax(amount + PHONE_PRICE) <= bank_balance)
or even
while (amount + PHONE_PRICE + ACCESSORY_PRICE + calculateTax(amount + PHONE_PRICE + ACCESSORY_PRICE)<= bank_balance)
Although I have to admit that I'm not sure what the purpose of the SPENDING_THRESHOLD is.
You keep adding new phones and accessories until it reaches the total amount. I guess total cost becomes very close to the amount hence when you add the tax on top of that it crosses the limit and you see that message. I would suggest you to compare(in the while loop) the phone price along with the tax. Something like:
while (amount + PHONE_PRICE + calculateTax( PHONE_PRICE ) < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE + calculateTax( PHONE_PRICE );
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
Refer https://jsfiddle.net/Lxwscbbq/
Open the browser console to see the messages.
Program is not wrong it is simple:
var bank_balance = 303.91;
which is global. Suppose you provided
amount = 200;
amount = amount + calculateTax( amount );
amount = 200 + calculateTax(200);
if you check condition and you can see amount is grater than entered amount. Thats why you are getting "You can't afford purchase"
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

JavaScript Assignment - Conditionals (IF/Else Statements)

The basis of the assignment is to use the if/else if statements to set up the script. I need a little help finishing up the if/else part and for someone to look over any errors. Here's the assignment:
Write the JavaScript code in one HTML document using IF, and IF/Else statements for the following three situations. For each one make sure to write comments for each section.
Determine tax rate based on income and what the tax would be on the income.
Variable declarations section
1. Declare a variable that holds the income amount entered by the user.
2. Declare a variable that holds the minimum income that will not be charged taxes.
3. Declare a variable that holds the tax percentage for tax bracket 1.
4. Declare a variable that holds the tax percentage for tax bracket 2.
5. Declare a variable that holds the highest income for tax bracket 1.
6. Declare a variable that holds the highest income for tax bracket 2.
Assignments section
7. Assign $1500 as the highest income amount that will not be charged taxes.
8. Assign the highest income for tax bracket 1 to be $25K and the tax percent to 15%. Anything over $25K is in the next tax bracket.
9. Assign the highest income for tax bracket 2 to be $40K and the tax percent to 20%. Anything over $40K is in the next tax bracket.
10. Ask the user to enter a dollar amount.
11. Convert the data entered into a number.
Logic and Output section
12. Use only variables in your logic.
13. Determine whether or not the dollar amount entered is taxable.
14. Determine whether or not the dollar amount is in tax bracket 1 or 2.
15. Calculate the amount of tax on the dollar amount and display a message that tells the user what the tax amount would be on the number they entered.
16. For amounts greater than $40k display the message “I do not have the data to calculate the tax on this income.
Testing: Try values that are equal to the highest income for each bracket and the highest income for no taxes. Try numbers greater than the 40,000. Try amounts like 25,001 or 40,001.
My code thus far:
<script type="text/javascript">
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.","");
minIncomeNoTax = 1500;
taxPercentBrack1 = 15/100;
taxPercentBrack2 = 20/100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack2)
{
alert("Your income is taxable.");
}
else if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack1)
{
alert("Your income amount is in tax bracket 1.");
}
else if (userIncome >hiIncomeBrack1 && userIncome <=hiIncomeBrack2)
{
alert("Your income amount is in tax bracket 2.");
}
else
{
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
// output
document.write("Your Income: $" +userIncome + "<br />");
</script>
I fixed your if/else statement, and it seems to work now. I put it on jsfiddle:
http://jsfiddle.net/gXQXG/13/
Your issue was
if (userIncome <=1500 && userIncome >=40000)
else if (userIncome <=1500 && userIncome >=25000)
else if (userIncome <=25001 && userIncome >=40000)
The second statement in all three should be <=
A number cannot be both less than 1500 and greater than 4000 ;)
Next Step
You should replace the constants 1500, 25000, and 40000 with the variables you declared, hiIncomeBrack1 and hiIncomeBrack2
Lastly, there is one more issue in your logic, but, I will let you find that one. It has to do with two of the <= needing to actually be a <
Updated Code
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
var totalTaxDue;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.", 0);
minIncomeNoTax = 1500;
taxPercentBrack1 = 15 / 100;
taxPercentBrack2 = 20 / 100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >= minIncomeNoTax && userIncome <= hiIncomeBrack2)
{ //The user's income falls within our range of knowledge.
alert("Your income is taxable.");
if (userIncome >= minIncomeNoTax && userIncome < hiIncomeBrack1)
{ //The user falls into our first bracket
alert("Your income amount is in tax bracket 1.");
currentTaxBracket = taxPercentBrack1;
}
else if (userIncome >= hiIncomeBrack1 && userIncome <= hiIncomeBrack2)
{ //The user falls into our second bracket
alert("Your income amount is in tax bracket 2.");
currentTaxBracket = taxPercentBrack2;
}
}
else
{ //Can't help this user, they are not within our limits.
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
//Figure out the actual amount due
//Need to use parseInt to convert from string to int.(User types a string into the prompt.)
totalTaxDue = currentTaxBracket * parseInt(userIncome);
// output
document.write("Your Income: $" + userIncome + "<br />");
//Multiply the decimal tax rate by 100 so we can print out a nice and clean %.
document.write("Your Tax Percent: " + (currentTaxBracket * 100) + "%<br />");
document.write("Pay Uncle Sam: $" + totalTaxDue + "<br />");

Categories

Resources