I'm trying to have the price show in JavaScript when my button is clicked but it is just showing me my alert. Can anyone tell me where I went wrong? This is my function:
function prompttotalCost() {
var totalCost;
var costPerCD;
var numCDs;
numCDS = prompt("Enter the number of Melanie's CDs you want to buy");
if (numCDS > 0) {
totalCost = totalCost + (costPerCD * numCDs);
alert("totalCost+(costPerCD*numCDs)");
totalCost = 0;
costPerCD = 5;
numCDs = 0;
} else {
alert("0 is NOT a valid purchase quantity. Please press 'OK' and try again");
} // end if
} // end function prompttotalCost
The problem is that numCDs is a string, not a number, because prompt returns a string. You can e.g. use parseInt to convert it to a number:
numCDS = parseInt(prompt("Enter the number of Melanie's CDs you want to buy"));
Next thing: You are not assigning a value to totalCost before using it – that's bad. Either change var totalCost; to var totalCost = 0; or change totalCost = totalCost + (costPerCD * numCDs); to totalCost = (costPerCD * numCDs);.
Also, in your alert invocation, you are putting something that you want to be executed as code into a string. Change
alert("totalCost+(costPerCD*numCDs)");
to something like this:
alert("totalCost is "+totalCost);
Related
I m not sure what i m doing wrong. Thanks in advance for helping me in this matter.
var sum = 0;
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
Declare sum to zero each time you are executing the sum of items. Or else it will keep on adding to the sum that was calculated in previous iteration.
Also your submitprice seems to be undefined. I have initilaized it as an empty array.
Working Fiddle
var sum = 0;
var pricecheck = 35;
const submitprice = [];
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
var num1 = parseInt(userinput);
submitprice.push(num1);
sum = 0;
for (i = 0; i < submitprice.length; i++) {
sum += submitprice[i];
}
}
alert("free shipping.");
To start, you need to create an empty array to store the totals in. For this, I will call it "cart":
var cart = [];
Next, I would suggest creating an if statement to check if the input is a number:
var num1 = parseInt(userinput);
if(isNaN(userinput){
alert("Please enter a number");
continue;
}
You don't need the for loop to add the input to the sum, just remove the loop:
sum += userinput
After the loop, you would push to the cart:
cart.push(num1)
Finally, you need to check if the sum is more than free shipping
if(sum >= pricecheck) {
alert("You qualify for free shipping!")'
}
Then just output the result to the console with a pipe (|) concatenated between the numbers.
console.log(cart.join(" | ")
var sum = 0;
var cart = [];
var pricecheck = 35;
while (sum < pricecheck) {
var userinput = prompt("Please enter the cost of the item...");
if (userinput === null) {
break;
}
var num1 = parseInt(userinput);
if (isNaN(userinput)) {
alert("Please enter a number");
continue;
}
cart.push(num1);
sum += num1;
}
if (sum >= pricecheck) {
alert("free shipping.");
}
I took a look at this assignment again to refresh on what was asked for this question. You do not need to have that for loop at all within the while loop. Within each iteration of the while loop, you are asking the user for the price of their next item, adding it to the shopping cart, and also adding it to a running total (this total being your "sum"). This running total does not need to be re-calculated each time inside of the while loop because you would have done that in a single line. You are trying to calculate the price, starting at 0, each time you loop through the while loop (using your for loop). But this is not needed as you already have a running total that can be added to each time the user enters a value.
"Austin Caron" explained it well but for this assignment we do not need to do user authentication.
P.S. Try your best to avoid asking questions directly about an assignment and ask more general questions about a concept or idea you are struggling with.
I will try to explain it better. I rewrote a code, to make it better as an example. As you can see I have an app to generate a number, but to generate correct number I have to click 5-15 times on a button, due to random and if statement. I want to ask how to make a process to skip incorrect numbers and give an actual answers ( which took 5-15 clicks ) only in one click. I can give more information, if you didn't understand me. Thank you very much!
*video: https://vimeo.com/251109159
function getnumber() {
var input = document.IX.onetoThou.value;
var firstNum = input[0];
var ranNumb = Math.floor(Math.random()*(99-00+1)+00);
var ans = "you are right!";
var newNumber = firstNum + ranNumb;
if ( newNumber % 5 == 0){
document.getElementById("newnumber").innerHTML = newNumber+" "+ans;
}
}
You can wrap the generation of your number inside a do while loop:
function getnumber() {
var input = document.IX.onetoThou.value;
var firstNum = input[0];
var ans = "you are right!";
var newNumber;
do {
var ranNumb = Math.floor(Math.random()*(99-00+1)+00);
newNumber = firstNum + ranNumb;
} while (newNumber % 5 !== 0);
document.getElementById("newnumber").innerHTML = newNumber+" "+ans;
}
Instead of generating a random integer in [0, 100) and checking to see if it's a multiple of 5, generate a random integer in [0, 20) and multiply it by 5. That guarantees that your result will be a multiple of 5 between 0 and 100.
var ranNumb = Math.floor(Math.random() * 20) * 5;
hope this might help. You have to use if-else rather then if conditional statement
function getnumber() {
var input = document.IX.onetoThou.value;
var firstNum = input[0];
var ranNumb = Math.floor(Math.random()*(99-00+1)+00);
var ans = "you are right!";
var newNumber = firstNum + ranNumb;
if ( newNumber % 5 == 0){
document.getElementById("newnumber").innerHTML = newNumber+" "+ans;
}else{
document.getElementById("newnumber").innerHTML = "You are wrong";
}
}
When I Input the first number to be for example 5 and the second Number to be like 10 I get undefined. I tried alert(array); to see the contents of it but there was nothing and hence undefined. It works for other numbers like 1 to 9. Why does it give me an undefined value from range 5 to 10? I just want to make a random number chooser where you will input the first number and the second number and a random number will be given to you?
function promptUser() {
var first = prompt("First number?");
var second = prompt("Second number?");
var array = [];
//Make a range from First number to last number then choose a random number
for (x = first; x <= second; x++) {
array.push(x);
}
alert(array);
randomInt = Math.floor(Math.random() * array.length);
alert("The random number is " + array[randomInt]);
}
prompt() returns the result in string literal, you need to use parseInt() or other methods to convert string to Number.
var first = parseInt(prompt("First number?"), 10);
var second = parseInt(prompt("Second number?"), 10);
var array = [];
for (x = first; x <= second; x++) {
array.push(x);
}
randomInt = Math.floor(Math.random() * array.length);
console.log(array, randomInt, "The random number is " + array[randomInt]);
Additionally, alert() is not a debugging tool, Learn to use Console
your first number is being treated as string needed to be parsed as int
function promptUser(){
var first = prompt("First number?");
var second = prompt("Second number?");
var array = [];
<!--Make a range from First number to last number then choose a random number-->
for (x = parseInt(first); x <= parseInt(second); x++){
array.push(x);
}
console.log(array);
randomInt = Math.floor(Math.random()*array.length);
console.log(randomInt);
alert("The random number is " + array[randomInt]);
}
promptUser();
Use:
var first = parseInt(prompt("First number?"));
var second = parseInt(prompt("Second number?"));
instead of:
var first = prompt("First number?");
var second = prompt("Second number?");
prompt returns string
I want to be able to have a user enter multiple grades and then have the Javascript to average those grades that are entered. When the user is done entering grades, they can click cancel and close the Propmt Box, and if they don't enter any grades at all (defaults at 0), then the program displays that there were no grades entered.
I'm pretty new at this! I'm taking a javascript course at my College, and it's a bit confusing because the teacher doesn't teach! All we have to reference to is W3schools, which this stuff isn't listed at all!
Here's another explanation:
"Develop a program to allow a teacher to enter an arbitrary number of grades, perform an average calculation and then display the result in a grammatical sentence. The program must also tell the user if no grades were entered. You are required to use a loop and an “if else” statement. Be sure to declare all variables and test for the possibility of division by zero."
<script type = "text/javascript">
var gradeCounter = 0,
gradeValue = 0,
total = 0,
average, grade;
var sum = 0;
var i = 0;
while (gradeValue != -1 && gradeValue <= 100) {
//Prompt the user
grade = prompt("Enter Grades, -1 to Quit:", "0");
//Parse the prompt result to a int
sum += parseInt(grade);
i++;
if (i >= 0 && grade != null) {
document.getElementById("average").innerHTML = "The average of the grades you've entered are " + sum / i + ".";
} else {
document.getElementById("error").innerHTML = "There were no grades entered";
}
} </script>
Thanks again!
this does ok
updated
updated again
JSFIDDLE
// note: the dom must be ready before execution
var btn = document.querySelector('button'),
res = document.getElementById('average');
btn.addEventListener('click', function(e) {
var val = prompt('Enter comma delimited grades to average');
val = val.length ? val.replace(/\s/g, '').split(',') : '';
var count = val.length || 0; // no 0 division
if (!count) {
res.innerHTML = 'you must enter comma delimited numbers to average';
return;
} else {
var average = val.reduce(function(a, b) { // is a loop
return +a + +b;
});
res.innerHTML = (average /= count).toFixed(1);
}
});
html
<button id="avgBtn">Prompt</button>
<p>Average: <span id="average"></span></p>
var grades = [];
// initialize the array that will store the entries
var sum = 0;
// initialize the variable that will add the array values together
var average;
// initialize the variable that will contain the final result
var invalid = [];
// initialize the variable that will be used to make sure the user inserts something
for (i = 0; i < 5; i++) {
// repeat the following code 5 times
grades[i] = prompt("Please enter a grade. (You will be asked for 5 grades)", "");
// ask the user for a grade and store it to the array
}
for (i = 0; i < grades.length; i++) {
if (grades[i] === "" || grades[i] === null) {
invalid[invalid.length] = grades[i];
}
}
if (invalid.length !== 5) {
for (i = 0; i < grades.length; i++) {
// repeat this code the same amount of times as there are entries in the array (5)
sum += Number(grades[i]);
// add the entries together. make sure they are numbers using the Number() function
}
var average = sum / grades.length;
// divide the added entries by the number of entries (again, 5)
alert("The average of all of your numbers is: " + average);
// alert the user of the completed average
} else {
alert('You need to enter grades for this to work! Please reload the page to try again.');
}
I've just started learning coding on code academy and I'm really new to this.
I'm trying to make this program ask the user for values which it adds to an array from which it calculates the sample standard deviation.
// This array stores the values needed
var figures;
getStandardDeviation = function() {
// I need at least two figures for a standard deviation
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
// Checks whether user wishes to add more values to the array
var confirm = prompt("Would you like to add another? (Y or N)").toUpperCase();
// I can't figure out why the following if statement is not executed
// It checks whether the user wishes to add more values and adds them to the array
// If not it breaks the for loop
if (confirm === "Y"){
for ( i = 0; i === 100; i++){
figures[i + 2] = prompt("Enter a number:");
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
// The rest of the code works fine from here onwards
var sumx = 0;
var n = figures.length;
for(var i = 0 ; i < n ; i++) {
sumx += figures[i];
}
console.log("Sum = " + sumx);
var sumXsq = 0;
for( i = 0 ; i < n ; i++) {
sumXsq += (figures[i] * figures[i]);
}
console.log("Sum x squared = " + sumXsq);
var sxx = (sumXsq - (sumx * sumx)/n);
console.log("Sxx = " + sxx);
var v = sxx/(n - 1);
console.log("Variance = " + v);
var standardDev = Math.sqrt(v);
console.log("Standard Deviation = " + standardDev);
};
getStandardDeviation();
The program is supposed to ask me if I want to add more values to the array, then when I confirm, it gives me a prompt to add more values.
Currently, when I execute the program I input the numbers 56 and 67. The code then asks me if I wish to add more values, I then confirm this. Instead of letting me add more values it ignores this and calculates the standard deviation with the first two values (56 and 67).
The output is:
Sum = 05667
Sum x squared = 7625
Sxx = -16049819.5
Variance = -16049819.5
Standard Deviation = NaN
for ( i = 0; i === 100; i++){[...]} means
Set i to 0
If it's not true that i === 100 (that is: if i is not 100), end the loop
Do whatever I put inside the {} braces, once
Do i++
Back to 2
As the initial value for i is 0 and not 100, the code inside the loop is never executed. If you want it to go from 0 to 99, it should be for ( i = 0; i < 100; i++).
You don't actually need a for loop, though. A while loop would be better. A loop like while (true){[...]} would run until it hit a break statement. As you wouldn't have the i in that case, you could use figures.push(parseFloat(prompt("Enter a number:"))) instead (you should use parseFloat, as per what Vincent Hogendoorn said) . push adds a new value at the end of an array, so it's exactly what you need. Something like:
if (confirm === "Y"){
while (true){
figures.push(parseFloat(prompt("Enter a number:")));
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
You could also change it so it doesn't ask if you want to stop if you don't have at least two values. That way you would be able to leave out that first part:
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
indeed your figures variable isn't defined as an array, like #James Donnely says.
Keep in mind you also fill in strings, so if you want to add up values you have to convert them to values.
you can use something like parseFloat for this.
if you don't use it, you sum up strings. 3+4 will be 34 instead of 7.
Your figures variable isn't defined as an array. Because of this figure[1] = prompt(...) never gets hit and a TypeError is thrown on var n = figures.length;.
Change:
var figures;
To:
var figures = [];
JSFiddle demo.
You can then replace the for loop you're using after if (confirm === "Y") with a recursive function:
// Push a user input number into the figures array
figures.push(prompt("Enter a number:"));
// Function to add a new number and ask if we want to add more
function addNewNumber() {
// Push a new user input number into the figures array
figures.push(prompt("Enter a number:"));
// Ask if the user wants to add another number
if (confirm("Do you want to add another number?"))
// If they do, call this function again
addNewNumber();
}
// Trigger the function for the first time
addNewNumber();
JSFiddle demo with recursion.
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);