Hello so I'm trying to get the += to increase value of balance. I now understand that in java script use += is to pass by reference, but how can I use it to pass by value.
alert("Welcome to the Online Bank Teller");
var balance = 100.00;
var amount;
var run = true;
do{
var pick = prompt("Make a selection...\n1-Check Balance, 2-Deposit, 3-Withdraw, 4-Quit");
if(pick == 1){alert("Your balance is: $" + balance.toFixed(2));}
else if(pick == 2){
amount = prompt("Enter the amount you want to deposit: $");
if(amount > 1000){alert("You can only enter up to $1000 per deposit!");}
Right here--->balance += amount;
alert("Your new balance: $" + balance.toFixed(2));
}
else if(pick == 3){
amount = prompt("Enter the amount you want to withdraw: $");
if(amount > balance){alert("Amount exceeded account balance!");}
else if(amount > 500){alert("The max you can take out is up to $500 per withdraw!");}
else if (amount <= balance){
balance -= amount;
alert("Your new balance: $" + balance.toFixed(2));
}
}
else if(pick == 4){run = false;}
else{alert("Not a valid choice!");}
}while(run)
How can I get it to alter the value inside of the variable when the user enters a new deposit.
I get
Your balance is: $10022
instead of
Your balance is: $122
Thanks in advance...
use parseInt() function to each amount which is getting from prompt
amount = parseInt(prompt("Enter the amount you want to deposit: $"), 10);
DEMO
Try
balance = parseInt(balance) += parseInt(amount);
Balance and amount are strings, so for example:
Adding the string '50' to the string of '3' woul make '503'
Adding the float value of '50' to the float value of '3' would make '53'
As an alternative to the parseInt function that has already been mentioned, there are some "quick&dirty" ways to do it:
amount = 1 * prompt("Enter the amount you want to deposit: $");
// get'S converted because * is only defined on numbers
amount = +prompt("Enter the amount you want to deposit: $");
// converted because unary + is only defined on numbers
and a couple of other, less common ones.
Adding a string to a number with += operator produces a string.
prompt() returns a string, hence you need to convert the return values to a number:
balance += +amount;
Or use parseFloat() to convert values. Though I can't understand how you'd get anything alerted, since strings haven't toFixed() method, and hence the alert() in your code is supposed to trigger an error.
Related
Im in the process of learning javascript and I cant seem to understand why the break statement isnt functioning :( Can someone please tell me what I've done wrong?
let maximum = parseInt(prompt("Enter the maximum number"));
while(!maximum){
maximum = parseInt(prompt("Enter a valid number"));
}
const randomNum = Math.floor(Math.random() * maximum) + 1;
console.log(randomNum);
let guess = parseInt(prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`));
let attempts = 1;
while (parseInt(guess) !== randomNum){
if (guess === 'q') break;
attempts++;
if(guess > randomNum){
guess = prompt("Too high, guess again.");
} else{
guess = prompt("Too low, guess again.");
}
}
if (guess === 'q'){
console.log("Quitting.")
} else {
console.log(`It took you ${attempts} amounts of guesses!`)
}
if (guess === 'q')
You are parsing the value to an integer and are comparing it to a string. Which is always false
So when you type 'q' in your prompt and try parseInt on it you will get NaN which stands for not a number. And NaN is not equal with q obviously
EDIT:
as #axic correctly pointed out the condition from above cannot be fulfilled if q was typed before the iteration begins. But that brings another problem:
On the third iteration you will get another prompt saying "Too low, guess again." even if you guessed the right number, because guess is string and compared to a number which will return false in all cases.
You are parsing the value to an integer and are comparing it to a string.
let maximum = parseInt(prompt("Enter the maximum number"));
while (!maximum) {
maximum = parseInt(prompt("Enter a valid number"));
}
const randomNum = Math.floor(Math.random() * maximum) + 1;
console.log(randomNum);
let guess = prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`);
let attempts = 1;
while (parseInt(guess) !== randomNum) {
if (guess === 'q') break;
attempts++;
if (guess > randomNum) {
guess = prompt("Too high, guess again.");
} else {
guess = prompt("Too low, guess again.");
}
}
if (guess === 'q') {
console.log("Quitting.")
} else {
console.log(`It took you ${attempts} amounts of guesses!`)
}
The break statement works totally fine, the issue is in a different location of your logic. You are parsing the integer of guess when displaying the first prompt to enter a guess for the number but when entering anything that isn't a number the value will simply be NaN.
Line 7 is:
let guess = parseInt(prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`));
but should be:
let guess = prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`);
I'm not entirely sure if this is what you want to achieve but based on the little information you gave I assumed that this would be what you're trying to get.
I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
I'm creating a Javascript program where the user will be asked how much pounds (£) they'd like to convert into Euros. The program should check if the number of pounds is greater than 0 and a number. If the input is 0 or a negative number or the input is not a number then an error message should be displayed – “input error, please input a number greater than 0”.
If the pounds to be exchanged is > £500 then no commission is charged. If the number of pounds worked is < = £500 then 3% commission is charged.
An output message should be displayed to show the number of euros exchanged.
P.s Amateur js programmer
const exchange = 1.19;
var pounds = 0;
var euros = 0.0;
pounds = prompt("Enter the amount of pounds you wish to convert": );
if (pounds <= 0) {
error_message = ("Input error! Please input a number greater than 0!");
} else if (pounds > 500) {
euros = (pounds * exchange);
alert(euros);
} else {
euros = (pounds * exchange);
euros = (euros - ((euros / 100) * 3));
alert(euros);
}
Everything what you get from the prompt is string.
You can parse your pound into the number with parseInt or parseFloat functions.
const exchange = 1.19;
var euros = 0.0;
var text = prompt("Enter the amount of pounds you wish to convert: ");
const pounds = parseFloat(text);
if (pounds <= 0) {
error_message = ("Input error! Please input a number greater than 0!");
} else if (pounds > 500) {
euros = pounds * exchange;
alert(euros);
} else {
euros = (pounds * exchange);
euros = (euros - ((euros / 100) * 3));
alert(euros);
}
The prompt is a string, as it returns a string (even though ou desire a number)
To convert it, use the Number constructor (or function)
try this:
pounds = prompt("Enter the amount of pounds you wish to convert");
pounds = Number(pounds);
or, you could cast it using the + sign
pounds = +pounds;
In my code, how can I add the if statement so it print different statements depend on different situtation. for example, I like to have a statement for the sum < 1, and else sum > 1. I try w3 school but the example if statement does not work for some reason
<!DOCTYPE html>
<!-- Network Latency Calculator -->
<html>
<head>
<meta charset = "utf-8">
<title>Network Latency Calculation</title>
<script>
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var thirdNumber; // third string entered by user
var fourthNumber; // fourth string entered by user
var number1; // first number to add
var number2; // second number to add
var number3; // third number to add
var number4; // fourth number to add
var sum; // sum of number1 and number2 and number3 and number4
// read in first number from user as a string
firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );
// read in third number from user as a string
thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );
// read in fourth number from user as a string
fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
number3 = parseInt( thirdNumber );
number4 = parseInt( fourthNumber );
sum = number1 + number2 + number3 + number4; // add the numbers
// display the results
document.writeln( "<h1>The network latency is " + sum + "</h1>" );
</script>
First of all you might want to look here:
https://www.w3schools.com/jsref/met_doc_writeln.asp
Right now you writing in the head of the html not in the body
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<pre>
<script>
var NowDate = new Date();
var number1 = NowDate.getHours(); //added current hour 0-23
var number2 = 5; // second number to add
var number3 = 0.3; // third number to add
var sum = number1+number2*number3;
if (sum > 5){
document.write("That's a");
document.write(" big Sum ("+sum+")");
} else if (sum === 4) {
document.write("Sum =");
document.write(" 4");
}else{
document.write("Sum is ");
document.write("small ("+sum+")");
}
</script>
</pre>
<p>Note that writeln() add a new line after each statement:</p>
<pre>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</pre>
</body>
First off, judging by your short description on what you want, I understand you want the statement of whatever you want to say after you calculate the total. To do that, it is really easy.
Example:
sum = number1 + number2 + number3 + number4; // add the numbers
if(sum > 1){
//Your code
} else {
//Your code
}
The reason I didn't put else if because if the sum is greater than one, it runs whatever statement you want it to run. If it isn't, then it will run the other, the else statement.
If you want to look at more if/else examples, you can go on this StackOverflow post and check the examples they have and how to use it.
After you get the sum, you could add an if-statement similar to this code if you so desire:
if (sum < 1) {
document.write ("The sum is less than one");
} else if (sum > 1) {
document.write( "The sum is more than one");
}
If you have more questions about if-conditional statements O'Reilly has a number of excellent technical books dealing with JavaScript.
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var thirdNumber; // third string entered by user
var fourthNumber; // fourth string entered by user
var number1; // first number to add
var number2; // second number to add
var number3; // third number to add
var number4; // fourth number to add
var sum; // sum of number1 and number2 and number3 and number4
// read in first number from user as a string
firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );
// read in third number from user as a string
thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );
// read in fourth number from user as a string
fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
number3 = parseInt( thirdNumber );
number4 = parseInt( fourthNumber );
sum = number1 + number2 + number3 + number4; // add the numbers
if (sum < 1) {
document.write ("The sum is less than one");
} else if (sum > 1) {
document.write( "The sum is more than one");
}
// display the results
document.writeln( "<h1>The network latency is " + sum + "</h1>" );
I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}