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);
}
}
Related
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 have a nested loop that will work most of the time, but for one particular case it does not run at all.
Here is the value that is failing: 1, 3-5, 7-10, 22
JS code:
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = Range[0];
end = Range[Range.length-1];
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
When the failing value is entered, this is the result:
Range: 1
Result in loop: 1,
Range: 3,5
Result in loop: 1,3,
Result in loop: 1,3,4,
Result in loop: 1,3,4,5,
Range: 7,10 <--- Never goes inside the loop
Range: 22
Result in loop: 1,3,4,5,22,
Result: 1,3,4,5,22
I can't figure out why the 7-10 part is being skipped. Any help or explanation is greatly appreciated.
Here is the FIDDLE
You need use parseInt when work with integer here
start = parseInt(Range[0],10);
end = parseInt(Range[Range.length-1],10);
After splittng you get array with strings, and when you try compare "7" with "10" it compared as string and "7" always greater then "10", because char code for '7' greater than char code for '1' (first char in "10")
For converting to number you can use next function also: Number, parseInt or parseFloat
document.getElementById("myButton").addEventListener("click", function() {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = parseInt(Range[0], 10);
end = parseInt(Range[Range.length - 1], 10);
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
// Log is my imitation of console.log()
function Log(stuff) {
var msg = document.getElementById("msg");
var newDiv = document.createElement("div");
newDiv.innerHTML = stuff;
msg.appendChild(newDiv);
}
<p>Try this value in the input: 1, 3-5, 7-10, 22</p>
<input id="myIn" type="text" />
<button id="myButton" type="button">Go</button>
<p id="msg"></p>
Since you are using a text input field all values from that field are strings. Then you use string manipulations that return more string values. You are never dealing with numbers. So Javascript will treat them as string values when testing if one value is greater than the other.
You can use the Number global object to safely cast a string value to a number. The benefit of Number over parseInt and parseFloat is if any part of the string is non numeric it will return a NaN value whereas the other two will return as much of the string as a number up to the first non-numeric character.
start = Number(Range[0]);
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(', ');
}
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 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.