Can't quite get two variables to add and subtract properly. (Javascript) - javascript

Currently I'm trying to use prompts to assign an integer to variables, and then add/subtract based on if the input is a negative or positive value, currently it will add, but it won't subtract.
var creditLimit = parseInt(prompt("What is your credit limit?"))
var initialBalance = parseInt(prompt("What is your current balance?"))
var balanceChange = parseInt(prompt("Please enter a charge or a credit amount"))
var newBalance
if (balanceChange > 0) {
newBalance = initialBalance + balanceChange;
} else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
} else {
alert("Please enter a valid integer")
}
I know the alert could probably be something better, but right now I'm just breaking down a credit balance calculator and got held up at this spot.

else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
}
The balanceChange < 0 i.e it will be a negative value, so initialBalance - (- balanceChange) = initialBalance + balanceChange
that causing the problem here.

Ah, I just figured it out, I suppose I was trying to use a double negative operation by subtracting a negative input!

Related

How to get a JavaScript factorial programs' loop to show the working used?

Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}

How to check a postal code in JavaScript?

I am trying to find out if this person needs to pay for shipping costs.
What I did is divide the postal code into numbers and letters. Next, I check to see if the input is between 1000 and 2000 and between AA en BB.
Problem: When I type in postal code 1000AA or 2000BB or something in between I always get the else answer even when the if statement is correct.
var sendingCost = 15;
var city = prompt("What city do you live in?");
var postalCode = prompt("What is your postal code?");
var postalCodeC = postalCode.slice(0, 3);
var postalCodeL = postalCode.slice(4, 5);
if (city == 'Amsterdam' && postalCodeC >= 1000 && postalCodeC <= 2000 && postalCodeL >= 'AA' && postalCodeL <= 'BB') {
alert('There is no sending cost')
} else {
alert('The sending cost is €15.')
};
Your slice() is not taking all four numbers of the postal code. Instead, use the following postalCode.slice(0, 4).
Have a look at the Mozilla docs regarding slice.
In the working code snippet below also note the following three lines.
var postalCodeC = Number(postalCode.slice(0, 4));
// converts the alphanumeric value from prompt to a number for better comparison.
var postalCodeL = postalCode.slice(-2).toUpperCase();
// converts the letters of the postal code to CAPS, this way Aa, AA or aa will be valid too.
var correctCity = city.toLowerCase() === 'amsterdam';
// the same here, convert city to lowercase letters and compare the input to 'amsterdam'
Working example.
var sendingCost = 15;
var city = prompt("What city do you live in?");
var postalCode = prompt("What is your postal code?");
var postalCodeC = Number(postalCode.slice(0, 4));
var postalCodeL = postalCode.slice(-2).toUpperCase();
var correctCity = city.toLowerCase() === 'amsterdam';
var withinPostalArea = postalCodeC >= 1000 && postalCodeC <= 2000 && postalCodeL >= 'AA' && postalCodeL <= 'BB';
console.log(postalCodeC);
console.log(postalCodeL);
if (correctCity && withinPostalArea) {
alert('There is no sending cost');
} else {
alert('The sending cost is €' + sendingCost);
};
NOTE: In order to help you debug these issues. console.log() the output to check the value of the variable and see if it is what you expect it to be.
Try this
var postcodec = +postcode.slice(0, 4);
var postcodeL = postcode.slice(4, 6);
As #Ivar mentioned, I don't think you understand how works the slice function. The first argument should be the the begin position and the second should be the end position. Thus, if you want to select only the first 4 numbers, and then the 2 letters you should use :
let postcode = "1500BD";
//Also, simply using slice will return a string, thus, you may want to convert it using Number();
let num = Number(postcode.slice(0, 4));
let letters = postcode.slice(4);

javascript addition program displaying "NaN" error

My question is about this simple program always displaying a "NaN" error.
My code for this simple function will always alert a "NaN" error for a simple addition instruction and I'm not sure how to resolve this.
The program should simply add miles and the bonus, which is 1000 if futureTrips is any value greater than 0.
My code is:
var miles;
var futureTrips;
var totalMiles;
var bonus;
miles = prompt("Please enter your current miles");
futureTrips = prompt("pleae enter amount of future trips");
if (futureTrips > 0){
(bonus = 1000);}
else{
(bonus = 0);}
totalMiles = (bonus.value + miles.value);
alert(totalMiles);
This will always display a "NaN" error. Any tips on how to fix this issue?
Problem:
bonus and miles are numbers (miles in fact is a string). You have to use them not their .value property that doesn't exist (thus is undefined), so:
totalMiles = (bonus.value + miles.value);
is the same as:
totalMiles = (undefined + undefined);
which is NaN.
Fix:
Use bonus and miles directly (you still have to convert miles to a number though):
totalMiles = bonus + Number(miles);
Working snippett:
var miles;
var futureTrips;
var totalMiles;
var bonus;
miles = prompt("Please enter your current miles");
futureTrips = prompt("pleae enter amount of future trips");
futureTrips = Number(futureTrips);
if (futureTrips > 0) {
bonus = 1000;
} else {
bonus = 0;
}
totalMiles = bonus + Number(miles);
alert(totalMiles);
Notes:
prompt return strings, so you have to convert miles into a number first, otherwise you get a string concatenation instead of arithmitic addition. You don't have to convert bonus because it's already a number. You should also consider converting futureTrips to a number before the if.
Parenthesis are not necessary around expressions: (bonus = 1000); is equivalent to bonus = 1000;.
In JavaScript, prompt returns string value. You can not apply .value on them.
By default string values are converted to int before the addition with another integer (also known as coercing). But to be on the safe side you can use parseInt to convert string to int manually.
Change totalMiles = (bonus.value + miles.value); To
totalMiles = (bonus.value + parseInt(miles));
Try this:
var totalMiles;
var bonus;
var miles = parseInt(prompt("Please enter your current miles"),10);
var futureTrips = parseInt(prompt("pleae enter amount of future trips"),10);
if (futureTrips > 0) {
bonus = 1000;
} else {
bonus = 0;
}
totalMiles = bonus + miles;
alert(totalMiles);
I always use the radix in parseInt like paarseInt(miles,10). Or use parseFloat(miles).
Also don't use bonus.value or miles.value, just use miles since miles is the return string from then prompt command and bonus is a number.
miles is a string here. To get the value as an integer I suggest instead of miles.value do parseInt(miles)
Your code modified:
var miles;
var futureTrips;
var totalMiles;
var bonus;
do{
miles = prompt("Please enter your current miles") ; //assigns a string value to variable
futureTrips = prompt("pleae enter amount of future trips");
miles = parseInt(miles); //convert string to number
futureTrips = parseInt(futureTrips);
}while( isNaN(miles + futureTrips) ); //optional loop, repeat prompts if NaN detected
if (futureTrips > 0){
(bonus = 1000);}
else{
(bonus = 0);}
totalMiles = (bonus + miles); // removed bonus.value, did you mean to use the Object.ValueOf() method?
alert(totalMiles);

How to display an integer into a div

I am working on getting the user t input a number for something in this case it would be a resistor value, I have asked them via a prompt to pick a number and then if that number is within the limits I have set then the number would be displayed back to the user within a div.
I have built this already and got it to work with a couple of test messages so I believe the function itself is fine however I am having a problem that whenever the user enters a correct value that value isn't displayed but "undefined" is displayed instead.
This is the HTML I am testing,
<button onclick="R1Value()">Change Value</button>
<div id="test3"></div>
And this is the JavaScript function
function R1Value() {
var R1ValueEntered = prompt("please enter a value for R1:")
var R1 = parseInt(R1ValueEntered)
var display = document.getElementById('test3');
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1.value;
}
else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
}
I have placed into into a jsfiddle as even though there isn't a lot of code it may save you some time if you can have a look, http://jsfiddle.net/2ufnK/72/ I may be missing something simple but I can't seem to fix the problem.
Just remove .value :
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
}
FIDDLE
.value is undefined for integers. Remove that and your code will work fine.
You don't need the R1.value. Just calling R1 will return it's value.
you got an error here, you assign R1 value, not R1.value
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
}
I tried your code.
Besides that you might have missed a closing tag, it worked for me. You need to change these lines:
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1.value;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
to:
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
you don#t need to get the value of R1, because it already IS hte Value.
I hope i could help.
regards
Your problem is that you are never closing your <div> and you also call R1.value, which is basically calling .value on an integer, which is undefined. Try the following:
function R1Value() {
var R1ValueEntered = prompt("please enter a value for R1:")
var R1 = parseInt(R1ValueEntered)
var display = document.getElementById('test3');
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
}
<button onclick="R1Value()">Change Value</button>
<div id="test3"></div>

control random number with javascript

This is my intent,
Generate random number
Store in variable
Clear variable
Generate new number greater than previous
Store in variable
I understand
(Math.floor(Math.random()*100)+1)
For 1-100 but not sure how to accomplish what I want exactly.
The following will generate a random number and then find the next random number it finds that is greater than it (or equal to it if it is greater than or equal to 99):
var num = Math.floor(Math.random()*100)+1;
alert(num); //current number
var newNum;
while((newNum = Math.floor(Math.random()*100)+1) < num && newNum < 100);
alert(newNum); //new number > num (or == num if num >= 99)
use
var ran_val = 1;
// ... some code goes here
ran_val = (Math.floor(Math.random()*100) + ran_val)
if you have no upper limit on the random numbers,
ran_val = (Math.floor(Math.random()*(100-ran_val)) + ran_val)
otherwise.
fwiw, the random numbers you emulate this way are no longer uniformly distributed.
var numb1 = Math.floor(Math.random()*100)+1, //Generate random number
numb2 = 0;
while (numb2<numb1) {
numb2 = Math.floor(Math.random()*100)+2; // Generate new number greater than previous
}
FIDDLE
You need to have a global variable and a function that handles the random number generation.
You can do something like this:
var num = 1;
function generaterandom(){
num = Math.floor(Math.random()*100)+num;
}

Categories