JavaScript - Problem Regarding Arrays
Hey, I'm working on a problem and what I need the program to do is to add up the numbers in the array NOT add up how many numbers there are. There are 5 total numbers that a user will input. The counting of the numbers will be in a seperate method which will then return to the main. Then be displayed through system.out.println. I don't know where I am going wrong any help? Thanks!
Code: import javax.swing.*; import java.util.*; public class Question10 { public static void main (String []args) { //declares Scanner keyboard = new Scanner(System.in); int [] myNums = new int[5]; for (int i=0; i < myNums.length; i++) { System.out.println ("Please Enter Data"); myNums[i]= keyboard.nextInt(); } } //end main public static int getTotal(int inArray) { int a,b,c,d,e,f; f = a+b+c+d+e; return f; } }//end class Similar TutorialsIm working on a program where the user enters a line of numbers and then can either sort them in order or can display the minimum number. Both those seem to work, but for some reason I keep getting three -1 values in my array. So the minimum value is always -1 and when I sort it comes back -1-1-1[numbers i enter]. I cant seem to figure out why my code is doing that. Code: private int[] buildArray(String line) { int[]arr = new int[line.length()]; arr[0] = 0; for (int i = 1; i < line.length(); i++){ arr[i] = Character.digit(line.charAt(i),10); } return arr; } private int findMin(int numbers[]) { //PRE numbers.length >= 1 int min = numbers [0]; for (int i = 1; i < numbers.length; i++){ if (numbers [i] < min) { min = numbers [i]; } } return min; } private String makeString(int numbers[]) { //PRE numbers.length >= 1 int i = 0; String s1 = new String (""); while (i < numbers.length){ s1 = numbers[i] + s1; i++; } return s1; } private void sort(int numbers[]) { for (int i = 1; i< numbers.length; i++){ int j = i-1; int temp = numbers[i]; while (j >= 0 && temp > (numbers[j])){ numbers[j+1] = numbers[j]; j--; } numbers[j+1] = temp; } } Input: 3,1,2,88 output: Min Value = -1 Line 1 Sorted = -1-1-101288 Any type of help would be very appreciated, Im very new to this still. Hello everyone I am having trouble with a project i am supposed to be doing which is to turn structured English into coding joined with the code i am about to post !! This is the code i have written so far that works: var contestantNamesArray = ['Tom and Nazia', 'Pat and Dan', 'Sandra and Kofi', 'Ian and Adele', 'Paul and Costas']; var judgesPointsArray = [2,1,5,4,3]; var audiencePointsArray = [4,5,2,3,1]; var combinedPointsArray = new Array (5) for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { combinedPointsArray[couple] = judgesPointsArray[couple] + audiencePointsArray[couple]; } var maxCombinedPoints = 0; for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { if (combinedPointsArray[couple] > combinedPointsArray[maxCombinedPoints]) { maxCombinedPoints = couple; } } document.write('The maximum number of points was ' + combinedPointsArray[maxCombinedPoints] + '<BR>'); document.write('The couple(s) scoring the maximum were' + ':' + '<BR>'); Now with that code there i have just posted, I am supposed to take this structured English below and combine them together but cannot work out how to link or code it to get it to work. write out a heading for the list of couples scoring the maximum declare a variable to keep count of how many couples scored the maximum value and initialise it to zero for each couple if this couple scored the maximum write out the couple's names increase the count of couples who scored the maximum value end if if a dance-off is required write out that a dance-off is required else write out that a dance-off is not required end if end for I have tried myself but i am stuck at how to link the contestantNamesArray with the rest of the code in order to be able to display the couples who scored the maximum points and store it in a new variable and then write out the names. Sorry if i have posted wrongly this is my first time and i am a new learner to JavaScript trying to learn basics. Thank you anyone in advance and if you need any further information i will provide anything you need. Gary I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* Hello, I am new with Javascript and running into this problem that I don't understand. I define a base class that only contains an array "elements", and a derived class that contains nothing more (for simplicity): Code: function baseClass() { this.elements = new Array; } function derivedClass() { } derivedClass.prototype = new baseClass; Then I create two instances of the derived class, and add two elements in each: Code: a = new derivedClass(); a.elements.push("A"); a.elements.push("B"); b = new derivedClass(); b.elements.push("C"); b.elements.push("D"); When I examine the contents of these arrays, I see that both a.elements and b.elements contain {"A","B","C","D"} ! I.e. as if the two arrays are in fact the same array! But these are two separate instances of the class, I expect two separate arrays. Note that if instead I use the base class: Code: a = new baseClass(); a.elements.push("A"); a.elements.push("B"); b = new baseClass(); b.elements.push("C"); b.elements.push("D"); then I get a.elements = {"A","B"} and b.elements = {"C","D"}, as I would expect. Could someone explain to me the problem with using the derived class? Thank you, Stephanos Hi. I am fairly new to JavaScript. I am having some troubles with arrays. I am using Chrome 12 beta. Here is a brief version of the code I am having trouble with Code: var array=new Array() array[0]=new Array() array[0][1]=new Array() var array[0][1]=[ 3, 1, 4, 1, 5, 9, 2, 6, 5, ... ]; I do not want to use "array[0][1][n]" because my array has too many items to do that and it is just plain annoying to change the numbers that way. I get an error on the "var buffers[0][1]=[" line saying: "Uncaught SyntaxError: Unexpected token [" What is the problem in my code? Thank you ahead of time. ---mint Hi could someone help with this javascript. i dont know where to start with the script which is in bold. Program to report the results of an election. // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; // total votes -- to be initialised below var totalVotesArray; // Add code to // -- initialise totalVotesArray with a new empty array of the same size as candidateArray // -- use a for loop to add the online and paper votes for each candidate and store the result at the corresponding position in the total votes array. First of all thank you for reading my thread and giving time to help me. Here goes my question: How to sort this array? MY PRIORITY COLORS array: ------------ green , yellow ALL COLORS array : <---- this will be your main array. ----------------------- pink , green , orange THE RESULTS: ( the results after you sort) (Not sorted by alphabetically, but sorted by the priority colors) ---------------- green , pink , orange I hope you could help me solve this javascript sorting problem. Thank you! Code: <HTML> <HEAD> <TITLE>Listing 4.4</TITLE> <SCRIPT TYPE="text/javascript"> //DEFINE METHOD function displayInfo() { document.write("<H1>Employee Profile: " + this.data[0] + "</H1><HR /><PRE>"); document.writeln("Employee Number: " + this.data[1]); document.writeln("Social Security Number: " + this.data[2]); document.writeln("Annual Salary: " + this.data[3]); document.write("</PRE>"); } //DEFINE METHOD TO GET EMPLOYEE INFORMATION function getInfo() { var menu="0-Exit/1-Name/2-Emp. #/3-Soc. Sec. #/4-Salary"; var choice=prompt(menu,"0"); if (choice != null) { if ((choice < 0) || (choice > 4)) { alert ("Invalid choice"); this.getInfo(); } else { if (choice != "0") { this.data[choice-1]=prompt("Enter information",""); this.getInfo(); } } } } //DEFINE OBJECT function employee() { this.data = new Array(4); this.displayInfo=displayInfo; this.getInfo=getInfo; } newEmployee=new employee(); </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/javascript"> newEmployee.getInfo(); newEmployee.displayInfo(); </SCRIPT> </BODY> </HTML> I am currently taking a Javascript certification course, this is a exercise given (final code) I don't completely understand what is going on though, could someone explain to me Code: this.data[choice-1]=prompt("Enter information",""); that part? I don't understand why, [choice-1] I don't fully understand why an array is even needed here? hi i have two arrays and i need to know which strings are in both arrays. i know how to do the bit if the string is in both but i don't know how to compare them as such. thanks Do arrays retain its data outside of a function. The reason why i asked this is because i created a global array and then a function. In the function i assaigned values to the global array but when i try to access the global array it gives me a "undefined" or "null" error. Code: var myArray = new Array(); var count = 0; function populate(){ for(i=0; i < 5; i++){ myArray[i] = count++; } } I have a quick question with multiple array and random numbers. If i generate my random numbers in one array, how would i take a selection of those numbers and put them in another array? Ex: array 1: 25, 34, 38, 40, 22, 49 want to move numbers between 30 and 50 to another array. array 2: 34, 38, 40, 49 is it as simple as for loops and if statements setting the conditions? do i use a sorting method? (selection? bubble?) any help would be appreciated. is it possible to embed something like this Code: <object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='450' height='24'> <param name='movie' value='http://youtubemp3.tv/player/player.swf'> <param name='allowfullscreen' value='false'> <param name='allowscriptaccess' value='always'> <param name='wmode' value='transparent'> <param name='flashvars' value='file=http://youtubemp3.tv/mp3embed-oeduvhv516z9.mp3&duration='> <embed src='http://youtubemp3.tv/player/player.swf' width='450' height='24' allowscriptaccess='always' allowfullscreen='false' flashvars='file=http://youtubemp3.tv/mp3embed-oeduvhv516z9.mp3&duration=' /> </object> into a array that will randomly pull things from it like this Code: <input type = "button" value="Call Out a Target" onclick="myFunction()"></button> <div id = "demo1"></div> <div id = "demo2"></div> <script type="text/javascript"> function shuffle(array) { var n = array.length, k, t; if (n == 0) {return false}; while (--n) { k = Math.floor(Math.random() * (n+1)); t = array[n]; array[n] = array[k]; array[k] = t; } } function myFunction() { var myarray=["red","blue", "yellow", "orange"]; shuffle (myarray); document.getElementById("demo2").innerHTML = myarray[0]; } </script> Thanks!!! I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. Hi again folks! A code I did recently was that 10 football teams had to register and the program had to ask the question "please enter your team" ten times then show the display on screen. This code works fine and does it jobs but I realized that I did this program a long winded way (shown below) : <script type="text/javascript"> //ask to enter names var enteredteam1= prompt("Please enter first team.", ""); //each team is shown as different variable var enteredteam2= prompt("Please enter second team.", ""); var enteredteam3= prompt("Please enter third team.", ""); var enteredteam4= prompt("Please enter forth team.", ""); var enteredteam5= prompt("Please enter fifth team.", ""); var enteredteam6= prompt("Please enter sixth team.", ""); var enteredteam7= prompt("Please enter seventh team.", ""); var enteredteam8= prompt("Please enter eighth team.", ""); var enteredteam9= prompt("Please enter ninth team.", ""); var enteredteam10= prompt("Please enter final team.", ""); var team= []; team[1]= enteredteam1 //the team should equal the entered value for the space team[2]= enteredteam2 team[3]= enteredteam3 team[4]= enteredteam4 team[5]= enteredteam5 team[6]= enteredteam6 team[7]= enteredteam7 team[8]= enteredteam8 team[9]= enteredteam9 team[10]= enteredteam10 document.write("<h1>Registered Teams</h1>"); // display the teams on the screen beside number document.write("<b>1.</b>" + team[1]); //write the entered value on the screen document.write("<br><br><b>2.</b>" + team[2]); document.write("<br><br><b>3.</b>" + team[3]); document.write("<br><br><b>4.</b>" + team[4]); document.write("<br><br><b>5.</b>" + team[5]); document.write("<br><br><b>6.</b>" + team[6]); document.write("<br><br><b>7.</b>" + team[7]); document.write("<br><br><b>8.</b>" + team[8]); document.write("<br><br><b>9.</b>" + team[9]); document.write("<br><br><b>10.</b>" + team[10]); </script> I was wondering for future references could anyone suggest a simpler code to do something similar? For instance what if I wanted to ask the question but I didn't know how many teams were going to be entered. It would ask the question (enter your team) until the user clicked on a button saying "finished" or something. Once again, I am new to this field, so any code with comments would be helpful! Code: <script type="text/javascript"> var authors = ['Ernst Hemingway','Charlotte Bronte','Dante Alighieri','Emily Dickinson']; </script> <script type="text/javascript"> document.write('<p>The first author is <strong>'); document.write('authors[0] + '</strong> </p>'); </script> I'm getting a syntax error on the last line ? I can't see the error, I closed the strong tag, closed the p tag. Put the line in a string, why won't it write the string ? How do you format a if statment for a multidemensional array.
I have 2 arrays and I would like to compare the 2 arrays. If an element in array 1 is NOT in array 2 then I would like to display that element. In this case, I should only display the letter "c" but it doesn't work and I don't know why?? Here's my code: Code: <html><head> <script type="text/javascript"> function getValue(id){ var x=new Array("a","b","c","d","e"); var y=new Array("a","b","3","d","e"); var str=""; for (var i=0; i<x.length; i++){ for (var j=0; j<y.length; j++){ if (x[i] == y[j]){ break; }else{ //Check if reach the last element in the array 2 //If yes, then display that element in array 1 b/c not in array 2 if (y[j] == y.length-1){ str += x[i]; } } } } document.getElementById(id).innerHTML = str; } function init(){ getValue("info"); } </script> </head> <body onload="init()"> <h2 id="info"></h2> </body> </html> I am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. |