JavaScript - While Loop And For Loop
Hey guys i've just been following a few tutorials and learnt how to do a for loop and a while loop, what is the major difference between the two? they seem quite similar? I know while loops are laid out a hell of a lot easier in my opinion!
Similar TutorialsOk, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. Hello... Thanks for reading... I am getting an undefined error when i try to get a value from this array in the interior loop... Code: // This is the array I am trying to access AuditTable [0] = ["Visio Modifed date","Word Modified Date","User Status","User Comment","Last Audit","Audit Status","Audit Comment"] AuditTable [1] = ["11/23/2009 8:52:18 AM","missing","OK","user comment number 1","1/1/2009","ok","audit comment number 1"] AuditTable [2] = ["11/24/2009 12:21:19 AM","missing","Out of Date","Changes from 2008 not implemented","1/2/2009","Out of Date","needs update"] AuditTable [3] = ["11/22/2009 9:24:42 PM","missing","Incomplete","Document doesnt cover all possibilities","1/3/2009","Inadequate","needs update"] I have hard coded values and had success such as: Code: data = AuditTable[1][0] But when I put the vars associated with the loop in I get an undefined error - AuditTable[i] is undefined: Code: // produces error data = AuditTable[i][j] //Works but retrieves wrong data data = AuditTable[j][i] //Works but retrieves wrong data data = AuditTable[1][i] //Works but retrieves wrong data data = AuditTable[j][2] I must be trying to access the array incorrectly or something... I have defined all the vars, and tried many combinations, alerted the values of both vars so I can prove it is not a scope issue... Am I missing something obvious? Thanks much... Code: var reportArray=new Array(); var reportData, title, subTitle, data; for(i in parmarray)// loop thru AuditTable array and get values { title = '<div style="font-family:verdana; font-size:14px; font-weight:bold; margin:25px 0px 5px 30px">'; title += namearray[i][0]; title += '</div>'; reportArray.push(title);//Take compiled variable value and put it into array for(j=0; j < AuditTable[0].length; j++)// loop thru AuditTable array and get values { subTitle = AuditTable[0][j];//points to first row of AuditTable where the labels are data = AuditTable[1][0];//points to the current row where actual data is html = i + j +'<div style="font-family:verdana; font-size:12px; color:#696969; font-weight:bold; margin-left:30px;">'; html += subTitle; html += '</div><div style="font-family:verdana; font-size:12px; color:#a9a9a9; margin-left:30px; margin-bottom:10px">'; html += data; html += "</div>"; reportArray.push(html);// put results into array } } it wont loop, as long as you enter something in the name field it will submit. also how do i stop from submitting if all fields are not filled out? any help will be appreciated) ====== function checkForm(form) { var len = form.elements.length; var h=0; for (h=0; h<=len; h++){ if ((form.elements[h].value==null) || (form.elements[h].value=="")){ alert("Please enter "+document.myForm.elements[h].name); document.myForm.elements[h].focus(); return false; } return true; } } ===body-== <FORM NAME="myForm" METHOD="post" ACTION="http://ss1.prosofttraining.com/cgi-bin/process.pl"> Name:<BR> <INPUT TYPE="text" size="30" NAME="name"><br> Email address:<BR> <INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br> Phone number:<BR> <INPUT TYPE="text" size="30" NAME="phone number"><br> Fax number:<BR> <INPUT TYPE="text" size="30" NAME="fax number"><p> <INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);"> <INPUT TYPE="reset" VALUE="Reset Form"> </FORM> Hi, I am doing some studying and we was to create a small loop using either the for loop, while loop or do while loop. I chose to do the for loop because it was easier to understand, but I want to know how to do the same using the while loop. Here is the for loop I have, but I cant figure out how to change to while loop. Code: for (var i = 0; i < 5; ++i) { for (var j = i; j < 5; ++j) { document.write(j + ""); } document.write("<br />"); } output is equal to: 01234 1234 234 34 4 How do you make the same using a while loop? I have the following code which is almost completely working the way I need it to with the exception of the "downloadFile" value... Code: /*Regex list of download file extensions, pipe and backslash delimited. Looks for the period before the file type so it will work on download links with query parameters after it */ var downloadTypes = /\.pdf|\.doc|\.xls|\.zip|\.csv|\.ppt|\.rtf|\.pptx|\.docx|\.xlsx|\.wmv|\.mpg|\.exe|\.mp3|\.rar|\.wav/i; /*Regex list of on-site domains, pipe and backslash delimited. */ var onsiteDomains = /\mytestdomain1\.com|\mytestdomain2\.com|javascript|#/i; /*Used to unobtrusivly add events to objects*/ function unobtrusiveAddEvent (element,event,fn) { var old = (element[event]) ? element[event] : function () {}; element[event] = function () {fn(); old();}; } var links = document.links; if ( links ){ for(var i=0; i<links.length; i++) { if( links[i].href.match(downloadTypes) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('ev=download&eventPage=Download From: ' + escape( wa.currentDomain + wa.currentURL ) + '& downloadFile=' + escape( links[i] ) ); }); } if( !links[i].href.match(onsiteDomains) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('lk=1&ev=Exit Link'); }); } } } ...how do I grab the value of the href that was just clicked? links[i] is not working (it's just grabbing the href value of the last href in the loop). I am missing something simple for sure. Can anyone point out what I am missing? Thanks! For those who read my other thread I finally scratched together the code to take a value from an XML file and add it to a select box as an option. Ofcourse it only does it once so I need to loop it. It's kinda complex though, here's a function line to add one option: addOption(document.people_form.People,name2,office2) And here's the code in the head: <script type="text/javascript"> //load xml file if (window.ActiveXObject){ var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; //Enforce download of XML file first. IE only. } else if (document.implementation && document.implementation.createDocument) var xmlDoc= document.implementation.createDocument("","doc",null); if (typeof xmlDoc!="undefined") xmlDoc.load("namedata.xml"); //Regular expression used to match any non-whitespace character var notWhitespace = /\S/ function getnames(){ //Cache "messages" element of xml file var nameobj=xmlDoc.getElementsByTagName("list")[0] //REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla for (i=0;i<nameobj.childNodes.length;i++){ if ((nameobj.childNodes[i].nodeType == 3)&& (!notWhitespace.test(nameobj.childNodes[i].nodeValue))) { // that is, if it's a whitespace text node nameobj.removeChild(msgobj.childNodes[i]) i-- } } } if (typeof xmlDoc!="undefined"){ if (window.ActiveXObject) //if IE, simply execute script (due to async prop). getnames() else //else if NS6, execute script when XML object has loaded xmlDoc.onload=getnames } var name2=xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue; var office2=xmlDoc.getElementsByTagName("office")[0].firstChild.nodeValue; var officePH2=xmlDoc.getElementsByTagName("officePH")[0].firstChild.nodeValue; var mobile2=xmlDoc.getElementsByTagName("mobile")[0].firstChild.nodeValue; var email2=xmlDoc.getElementsByTagName("email")[0].firstChild.nodeValue; </script> <script type="text/javascript"> function addOption(selectbox,text,value ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } </script> Could anyone give me a pointer on how to loop this so that it loads one option after another from the XML file? Thanks. I have a form that shows or hides divs based on what is chosen in a dropdown. There are 4 divs but only one is shown and the other 3 hidden based on dropdown selection. Inside each div are checkboxes with items for sale. I want to reset the checkboxes to unchecked and the line total values to 0 if the div is hidden. I've got the checkboxes to reset but I can't figure out how to set the line total values to 0 (There are 14 total so I'm trying to loop thru all of them and reset them.) This is what I have in the loop Code: for (var i = 0; i < form.elements.length; i++ ) { if (form.elements[i].type == 'checkbox') { form.elements[i].checked = false; } } // set line_totals to 0 for (var j = 0; j< form.elements.length; j++ ) { if (form.elements [j].name.substring(0,10) == 'line_total') { form.elements[j].value = ''; } } Hi All, im trying to to use a for loop to loop through a drop down list of users and if there is a match between the user logged in and the drop down list i want to enable two fields, if the user logged in isnt in the drop down list i want to disable the two fields, but im having trouble looping through, iv tried ".value" with no avail.. heres my Script Code: var RequestingUser = document.getElementById('JoinersLeaversContent_cmbRequestingUser').text; var Authorisers = document.getElementById('JoinersLeaversContent_ddlAuthoriseId'); for (var i = 0; i < Authorisers.length; i++) { if (RequestingUser.text == Authorisers.value) { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = false; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = false; } else { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = true; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = true; } } So just to be clear, if the user logged in appears in the drop down box i want to enable the two fields, if they dont appear i want to disable the two fields Please help. Thank you Hello all. I am faitly new at programming and have run into a little problem. I want to create a script that creates 2 random numbers, stored in 2 different variables and then compare them to eachother. there is two possible outcome of that comparison, either they are different or they are alike. If they are different i want to randomize a new set or numbers and make a other comparement, also to keep track on how many times i have created numbers. If they are alike i want to display the numbers and how many tries it took to get a matching pair. atm it looks like this <html> <body> <script> var x=(Math.floor(Math.random()*6)+1); var y=(Math.floor(Math.random()*6)+1); //creates two random int between 1 and 6 var throws = 1; //keep tabs on how many times we have thrown the dices if(x!=y) { x=(Math.floor(Math.random()*6)+1); y=(Math.floor(Math.random()*6)+1); throws=throws+1 }else{ document.write("you have rolled a pair. Dice 1 is: " +x +" and Dice 2 is: " +y +" and it took " +throws +" tries to get a pair."); } </script> </body> </html> How to get that into a loop? a really confused newbie scripter Hello, I recently purchased a JavaScript book, and I am confused by one of it's examples. I was wondering if anybody could answer my question. Here is the example: for (loopCounter = 1; loopCounter<= 3; loopCounter++) { //execute this code } Now, what I need help with is the variable part. The book goes on to say: ""To keep track of how many times you have looped through the code, you need a variable to keep count" My question is: Why does the variable have the value of one and not another number? I'm very very new to JS, I understand that the loopCounter has to be les than or equal to 3 for the code to execute, and also that it is incremented by one each loop, but the book is not clear on why the value of the variable has been set to 1. If anybody could answer this question I would be very grateful, I hate moving onto the next stage of a book if I do not completely understand the previous topics. Thank you in advance Hi All, could you please help me. A have a little program and i need to count somehow how many times a while loop is ran. how could i do that? Thanks for your help apparently this is supposed to be a loop... I got it off another topic here and it made NOOOO sense Code: //dandavis's ES5 Array methods: (function ArrayMethods(){var o=Array.prototype,it,i, e=eval('( {map:Z0,r=[];for(;i<m;i++){if(i in t){r[i]=a.call(b,t[i],i,t);}}return r;},filter:Z0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i];}}return r;},every:Z0;return m&&t.filter(a,b).length==m;},some:Z1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return true;}}return false;},lastIndexOf:Zb||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l;}}return-1;},indexOf:Zb||0;for(;i<m;i++){if(i in t&&t[i]===a){return i;}}return-1;},reduce:Z0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t);}return r;},reduceRight:Zm-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t);}return r;},forEach:function(a,b){this.concat().map(a,b);return this;}})'.replace(/Z/g,"function(a,b){var t=this.concat(),m=t.length,i="));for(it in e){i=o[it];o[it]=i||e[it];} }());//end ArrayMethods() someone want to explain it to me? here is some more Code: (function(){var o=Array.prototype,it,i,e={ map:function(a,b){var t=this.concat(),m=t.length,i=0,r=[];for(;i<m;i++){if(i in t)r[i]=a.call(b,t[i],i,t)}return r}, filter:function(a,b){var t=this.concat(),m=t.length,i=0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i]}};return r}, every:function(a,b){var t=this.concat(),m=t.length,i=0;return m&&t.filter(a,b).length==m}, some:function(a,b){var t=this.concat(),m=t.length,i=1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return!0}}return!1}, lastIndexOf:function(a,b){var t=this.concat(),m=t.length,i=b||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l}}return-1}, indexOf:function(a,b){var t=this.concat(),m=t.length,i=b||0;for(;i<m;i++){if(i in t&&t[i]===a){return i}}return-1}, reduce:function(a,b){var t=this.concat(),m=t.length,i=0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t)}return r}, reduceRight:function(a,b){var t=this.concat(),m=t.length,i=m-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t)}return r}, forEach:function(a,b){this.concat().map(a,b)} };for(it in e){i=o[it];o[it]=i||e[it]}}()); //end Array.16 injection it has something to do with eval... whats eval? sigh I hate arrays this is so confusing to try and read >< I like to figure out in my ready made For Loop it out puts a list of names and amounts I want to figure out how to put in a colour scheme. such as having every second row in yellow highlight? here is my code Code: <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="list.js"></script> <script type="text/javascript"> total=0; for (var i=0; i<amount.length; i++) { total=total+amount[i]; } document.write(total); </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> <script type="text/javascript"> document.write('<table'+' border="1"'+' rules="row"'+'cellspacing="0">'+'<tr>'+'<th>Date</th>'+'<th>Amount</th>'+'<th>First Name</th>'+'<th>Last Name</th>'+'<th>Address</th>'+'</tr>'); for (var i=0; i<date.length; i++){ document.write('<tr>'+'<td>'+date[i]+'</td>'+'<td>'+amount[i]+'</td>'+'<td>'+firstName[i]+'</td>'+'<td>'+lastName[i]+'</td>'+'</tr>');} </script> </table> </div> Any suggestions on how to add the colour within the loops Trying to use a "for" loop to cycle through an array and compare values; if the values are equal, then it displays a message about the team, etc. Code: <html> <head> <title>Javascript Colors!</title> <script type="text/javascript"> var teamcolors = ["blue","orange","Auburn Tigers","Yuck!","black","red","Georgia Bulldogs","Congratulations!","yellow","black","Georgia Tech","Awesome!"] function changeBGColor() { document.body.bgColor = prompt("What color should the background be?","Put ANY color here!"); checkForTeamColors(); } function changeTXTColor() { document.getElementById("text").style.color = prompt("What color should the text be?","Put ANY color here!"); checkForTeamColors(); } function checkForTeamColors() { var bgcolor = document.body.bgColor var txtcolor = document.getElementById("text").style.color var loopcount = 1 while (loopcount <= 12) { if ( (bgcolor == teamcolors[loopcount] && txtcolor == teamcolors[loopcount + 1]) || (bgcolor == teamcolors[loopcount + 1] && txtcolor == teamcolors[loopcount]) ) { alert("You have picked the team colors of " + teamcolors[loopcount + 2] + ". " + taemcolors[loopcount+3]) } loopcount = loopcount + 4; } } </script> </head> <body> <p id="text" align="center">This text will change color if you want to. <br> Maybe try a certain combination, like Orange and Blue, or Red and Black?<br></p> <button onClick="changeBGColor()">Click me to change the BG Color!</button> <button onclick="changeTXTColor()">Click me to change the text Color!</button> <p id="variables"></p> <script type="text/javascript" document.getElementById("variables").innerHTML = ( bgcolor + " " + txtcolor ) </body> </html> Hi all, I have a problem where I'm trying to load data into multiple divs. They are payslips, so p1, goes into january, p2 into febuary etc. I want to onLoad them all so when the page is loaded they are all displayed. Every time I try this, the loop automatically goes to the last iteration, 6 in this example, so the only div that is loaded is p6. Here is my code: function replace(slip, year) { // table contains either 'bank' or 'intranet' xmlHttpReq.open("POST", "do_payslips_ajax.php", true); xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlHttpReq.onreadystatechange=function() { if(xmlHttpReq.readyState == 4) { document.getElementById("p" + slip).innerHTML = xmlHttpReq.responseText; } } xmlHttpReq.send(getquery(slip,year)); } function getquery(slip,year) { strQuery = "weekmonth=" + slip + "." + year; return strQuery; } function loadpayslips(year) { for (slip=1; slip<=6; slip++) { replace(slip, year); } } <label> <body onload = loadpayslips(11)> search</a> </label> <div id="p1"> /div> <div id="p2"> month 2</div> <div id="p3"> month 5</div> etc.. Any help would be appreciated. Thanks Building a shopping cart, at the moment I have 1 variable array. My JS gets values from hidden inputs when add to shopping cart is clicked. The JS then pushes them all into the array in order. I've managed to get the js code to replace innerHTML and add the array to the HTML to show the products, quantity and totals in a table. However its only showing the last product, price, and total in the array in the table. I need to get it to do this: Product: Quantity: Total: Product1 1 1 Product2 2 2 Product3 3 3 So basically I think I need to have my 3 for statements then plus 2 to each i instead of i++ to print out the products but that still doesn't solve my problem with printing every product in a vertical list, same with quantity and same with total. Heres the code Code: var cart= new Array(); function readInput(){ var prd=document.test.prd.value; var prc=document.test.prc.value; var qty=document.test.amount.value; var total= prc * qty; cart.push( prd ) cart.push( qty ) cart.push( total ); var lenp=cart.length; for(var i = 0; i<lenp-2; i++ ) { document.getElementById("product").innerHTML = cart[i]; } for(var i = 0; i<lenp-1; i++ ) { document.getElementById("qty").innerHTML = cart[i]; } for(var i = 0; i<lenp; i++ ) { document.getElementById("total").innerHTML = cart[i]; } } Code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="css\basic.css" /> <script language="JavaScript" src="test.js"></script> <title>Shopping Time</title> <body> <form name="test"> <input type="hidden" name="prd" value="Paper"> <p class="desc" value="Paper"> Product: Paper 1</p> <p class="desc"> <input type="hidden" name="prc" value="1.99"> Price: £1.99</p> <p class="desc"> Select Quantity: <select name="amount" onchange="quantity()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select></p> <p class="submit"> <input type="button" onclick="readInput();" value="Add To Cart" /> </p> </form> <table border="1px solid black" rules="ALL" frame="void" class="cart" width="100%"> <tr> <th> <p class="cart">Product:</p> </th> <th> <p class="cart">QTY:</p> </th> <th> <p class="cart">Total:</p> </th> </tr> <tr> <td class="test"> <div id="product"> <p class="cart">Product:</p> </div> </td> <td> <div id="qty"> <p class="cart">QTY:</p> </div> </td> <td> <div id="total"> <p class="cart">Total:</p> </div> </td> </tr> </table> </body> </html> Hi I am trying to create a while loop and I am having trouble with what to put in it so far I have: Code: function showSports(obj) { var groupId=obj.id.substring(0, 1); var indx=obj.id.substring(obj.id.indexOf('_')+1); var id=indx.substring(0, indx.length+1); var displayInfo = false; while (displayInfoTab) { if (indx == 1) { show ('footballInfo'); hide('soccerInfo'); hide('baseballInfo'); } if(indx == 2 ) { show( 'soccerdInfo'); hide('baseballInfo'); hide('footballInfo'); } if(indx == 3 ) { show( 'baseballInfo'); hide('footballInfo'); hide('soccerdInfo'); } displayInfo = true; } } It is supposed to be able to loop through the links below and show/hide depending on which link is selected. Code: <a id='1link_1a' title="football Tab" onclick='showSports(this);'><span >FootBall</span></a></li> <a id='1link_1b' title="soccer" onclick='showSports(this); changeTab(this);'><span>Soccer</span></a></li> <a id='1link_1c' title="baseball" onclick='showSports(this);'><span>Baseball</span></a></li> So this is what I have so far: Code: import java.util.Random; public class lotteryGame { public static void main(String args[]) throws Exception { int n=0; // counter for the amount of times played int t=0; // total amount of winnings int i=0; // number of matches int a; // first guess int b; // second guess int c; // third guess int d; // first number in the lottery int e; // second number in the lottery int f; // third number in the lottery Random rand = new Random(); while (n<100) // play the game for 100 times { a=rand.nextInt(9) + 1; // assign a random number to a b=rand.nextInt(9) + 1; c=rand.nextInt(9) + 1; System.out.println("Lottery Number"+a+b+c); d=rand.nextInt(9) + 1; e=rand.nextInt(9) + 1; f=rand.nextInt(9) + 1; System.out.println("Your guess"+d+e+f); if (a==d){ i=i+1; System.out.println(a+"is a match"); d=d+10; // if a=d then d is taken out of the range (1-9) } else if (a==e){ System.out.println(a+"is a match"); i=i+1; e=e+10; } else if (a==f){ System.out.println(a+"is a match"); i=i+1; f=f+10; } if (b==d){ System.out.println(b+"is a match"); i=i+1; d=d+10; } else if (b==e){ System.out.println(b+"is a match"); i=i+1; e=e+10; } else if (b==f){ System.out.println(b+"is a match"); i=i+1; f=f+10; } if (c==d){ System.out.println(c+"is a match"); i=i+1; d=d+10; } else if (c==e){ System.out.println(c+"is a match"); i=i+1; e=e+10; } else if (c==f){ System.out.println(c+"is a match"); i=i+1; f=f+10; } if (i==3){ if (a==d-10&&b==e-10&&c==f-10){ t=t+10000; System.out.println("You win!!!"); } else{ t=t+1000; System.out.println("You had 3 matches! You win $1000"); } } if (i==2){ t=t+50; System.out.println("You had 2 matches! You win $50"); } if (i==1){ t=t+10; System.out.println("You had 1 match! You win $10"); } } n=n+1; i=0; } } I don't know what is wrong with the program, It compiles fine but when I run it, it never stops. =/ I figure that Code: n=n+1 would be a counter to stop the while loop. Where do I place it so it can count everytime it runs. Or, What do I need to add in order for the program to stop running after 100 times? Thank You. =] |