Javascript Averaging Calculator(Multiple Values entered by the user) - javascript

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.');
}

Related

free shipping ... if shopping chart total is greater than $35 ... user input unless total is more $35 in JavaScript

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.

Show message "no score entered" if user inputs a specific number into a prompt

Currently my JSFiddle allows a user to input some exam scores one number at a time and shows the average and total score for the numbers they give. Currently, if they enter -999 into the box, it means they are finished entering numbers and the average and total can be calculated.
How can I edit this to make it so that if the user entered -999 as their first input it displays “No score entered.”?
<script>
function userInput() {
var examScores = 0;
var totScores = 0;
var i = 0;
var scores = [];
while (true) {
examScores = parseInt(prompt("Enter a score or enter -999 when you're finished: "));
if (examScores === -999 && scores.length === 0) {
document.getElementById("scores").innerHTML = "No score entered.";
break;
}
else if (examScores === -999) {
break;
}
else {
scores.push(examScores);
i++;
}
}
for(var i = 0; i < scores.length; i++) {
totScores = totScores + scores[i];
}
document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);
}
</script>
<h1>Exam Scores</h1>
<h3>Click to enter scores</h3>
<input type="button" value="Enter student scores" onclick="userInput()" />
<div id="scores"></div>
You need to return instead of just breaking the loop.
if (examScores === -999 && scores.length === 0) {
document.getElementById("scores").innerHTML = "No score entered.";
return;
}
Breaking the loop solely will cause the function execution to continue, hence always reaching
document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);
Since the above line is being executed, your own work will be overwritten. Returning from within the loop would end the execution of the function.

Checking random number variable against Javascript array values for match, not working

For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}

How to sum up distinct value using javascript

I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.

Find greatest value in array (in set of integers)

My friend asked me to help him with homework, and I'm stuck. Here is assignment:
user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)
Here is my code (it even doesn't work in jsfiddle, just in my file)
<button onclick="duzinaNiza()">Do it!</button>
and here is JavaScript
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:");
\\ prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.
P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...
That is because the input is a String, you have to parse it to a Integer. Like:
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Try this:
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
The problem is that you are comparing two strings, when you wanted to compare two numbers.
In other words, the following expression is LEGAL in javascript and evaluates to true:
if('4' > '393939393'){
//true! string '4' is greater than string '3' (first char of '393939393')
}
What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:
parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.
So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:
function duzinaNiza() {
var brClanova = +prompt("Enter the number of array elements:");
if (!brClanova)
return;
var niz = [];
for (var i=0; i < brClanova; i++) {
var redniBr = i + 1;
niz[i] = +prompt("Enter "+ redniBr + ". array number:");
}
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
}
I used the Unary Plus Operator for that.
Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
You will have:
var max = Math.max.apply(null, niz);
document.write("Greatest value in array is: " + max);
In that case, you don't even need the unary plus operator because Math.max takes care of that.
try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]
duzinaNiza = function () {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
var maximum;
for (i=0; i<brClanova; i++) {
var temp = +prompt("Enter "+ i+1 +". number:");
if(i===0) { maximum = temp }
else { maximum = (temp > maximum)?temp:maximum; }
}
alert("Greatest value in array is: " + maximum);
}
}
You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.
Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.
Your comment used the wrong characters- `('\' should be '//')
function duzinaNiza(){
var brClanova= prompt("Enter the number of array elements:");
if(brClanova>0){
var niz= new Array();
for(var i= 0;i<brClanova;i++){
var redniBr= i+1;
niz[i]= prompt("Enter "+ redniBr +". array number:");
//prompt for geting each array element
}
var maximum= niz[0];
for(var a= 0;a<brClanova;a++){
if(niz[a]-maximum>0){
maximum= niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
Modified Code JSFIDDLE
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}

Categories