Array looping

Hi,
I need to run several nested loops. Problem is, I only know how many nested ones to do at runtime (not compile). eg. want to do something like this
imagine I have an int[] array.
int[] r;
Someone else initialises and populates this. Now I now that r is 7 dimensional, but do not know at compiletime.
for (int a = 0;a<5;a++) {
for (int b = 0;b<6;b++) {
for (int c = 0;c<6;c++) {
for (int g=0;g<4;g++) {
r[0]=a;
r[1]=b;
r[6]=g;
etc.
How can i do this without hard coding in the looping structures such that this can handle an array of an arbitrary dimension (just single array though - not [][]).
Thanks for help.

My code above will have 5 nested iteration with 4 x 2 x 3 x 5 x 4
But one thing I don't get it.. when you compile, it won't compile because I note some part of code are messed up with the Jive syntax highlighting.
For example:
counter<i>++;
should be
counter[ i ]++;Gosh!
So here I re-post the code again:
public class x {
void doLoop(int[] looper) {
    int counter[] = new int[looper.length];
    int r[] = new int[looper.length];
    boolean keepLooping = true;
    while(keepLooping) {
       int i=0;
       while (true) {
           counter[ i ]++;
           if (counter [ i ] <= looper [ i ])
              break;
           else {
              counter=0;
if (i+1==looper.length) {
keepLooping = false;
break;
i++;
if (keepLooping) for (i=0; i<looper.length; i++) {
r[i] = counter[i];
System.out.print("r[" + i + "]=" + r[ i ] + " ");
// now do something with r[]
System.out.println("");
public void doSomething() {
int[] looper = new int[] { 4, 5, 3 ,2 ,4 };
doLoop(looper);
public static void main(String[] s) {
new x().doSomething();
Hope it would be all right this time...

Similar Messages

  • How to populate a table with array loop

    I'm looping an array object and as I loop, I'm calling a function and this function returns 6 items
    <CFLOOP  from="1" to="#ArrayLen(zz)#" index="k">
      <cfdump var="#zz[k].getLine()#"> <p>
    </CFLOOP > 
    The above cfdump will return something like:
    [empty string]
    street name1
    [empty string]
    [empty string]
    city1
    state1
    zip1
    [empty string]
    street name2
    Apartment AA
    [empty string]
    city2
    state2
    zip2
    street name 3
    Margenthaller Hall
    Suite 202
    city2
    state2
    zip2
    etc
    I need to insert these results into my address table while looping.
    When I did the following (see below), each record got repeated 12 times (not sure why)
    <CFLOOP  from="1" to="#ArrayLen(zz)#" index="k">  <cfdump var="#zz[k].getLine()#">
      <cfquery name="test" datasourece="MyDNS">
       INSERT INTO MyAddr (street1,street2,street3,city,state,zip)
       VALUES ('#zz[1].getLine()#', '#zz[2].getLine()#', '#zz[3].getLine()#', '#zz[4].getLine()#','#zz[5].getLine()#', '#zz[6].getLine()#')
    </cfquery>
    </CFLOOP >
    Is there a way? to do insert as I already got the address correctly while looping but not sure how can I use the return result in insert statement.
    Can anyone help?

    For what you seem to be doing here, the loop is unnecessary and causing the multiple inserts since the <cfquery...> is inside the insert, it will be executed for each and every iteration of the loop.
    You COULD put the loop inside the <cfquery...> to build the repeating part of your query I.E. the VALUES clause it seems in your case.  But, unless you would have different sized arrays I would just do what you are doing and explicitly calling each array element.  I.E. the zz[1]...zz[2]...zz[3]...etc. that you have.

  • Xml Array Loop

    HI All
    I was wondering if you could help I have some code that im
    using to loop through an xml file. It seems to work fine. But when
    you come to the end of the Array (i.e the last image) and then
    scroll backwards through the images in reverse it seems to get a
    bit laggy. I think my code needs optimizing its a bit spagetti
    like.

    HI All
    I was wondering if you could help I have some code that im
    using to loop through an xml file. It seems to work fine. But when
    you come to the end of the Array (i.e the last image) and then
    scroll backwards through the images in reverse it seems to get a
    bit laggy. I think my code needs optimizing its a bit spagetti
    like.

  • Arrays/Looping

    I am writing a stored procedure and I have 10 parms which are input parameters and they will either be null or have a value. Can I load this into some sort of array object and then loop through them in PL? I looked in the book that I have for arrays, but found nothing in the index. I am using Oracle 8I.
    Any assistance would be greatly appreciated!!

    I want to do different things based upon the value passed.
    If null do xxxx if not null do YYYY
    SO I always will have 10, but I want to different things based upon the value passed. If I can't loop, I will repeat the code 10 times in a giant IF statement.........

  • Array loop - assigning variables

    Hi All,
    This is similar to a question I previously had, (which kglad so kindly helped me with) so please bare with me.
    Here is the code:
    nor = Array(a, b, c);
    aVar = Array();
    aVar[0] = 0;
    aVar[1] = 0;
    aVar[2] = 0;
    for (i=0; i<nor.length; i++)
    nor[i].onRelease = function() {
        nor[i].ivar=i;
            aVar[this.ivar] = 1;
            trace(aVar[this.ivar]);  // this outputs "1" //
                for (i=0; i<nor.length; i++)
                    trace(aVar[i]);  // this outputs "0, 0, 0" //
    The problem is that when tracing the "aVar" array, one of them should be "1" (so I think)
    Any Ideas?
    Thank you

    ahhhh... of course.
    Thanks kglad. I really appreciate your help.
    *I did revise the code slightly for future/others use.
    nor = Array(a, b, c);
    aVar = Array();
    aVar[0] = 0;
    aVar[1] = 0;
    aVar[2] = 0;
    for (i=0; i<nor.length; i++)
      nor[i].ivar=i;
    for (i=0; i<nor.length; i++)
    nor[i].onRelease = function() {
            aVar[this.ivar] = 1;
            trace(aVar[this.ivar]);  // this outputs "1" //
                for (i=0; i<nor.length; i++)
                    trace(aVar[i]);  // this outputs "0, 0, 0" //

  • Array loop to change variables?

    The plan is to set up variables to react to a flashvars value like this:
    [code=html]<param name="flashvars" value="mainVars=1" />[/code]
    [code=actionscript]
    var videoArray:Array;
    var videoTitle:String;
    var videoFile:String;
    videoArray=[0,1];
    function onEnterFrame(){
        for(var i=videoArray.length-1;i>0;i++){
            while(i==_root.mainVar-1){
                if(i==0){
                    videoTitle="Show the video's change";
                    videoFile="VID";
                else if(i==1){
                    videoTitle="This is the second one";
                    videoFile="promo";
    [/code]
    There would be many mainVars (over 100, actually) and this setup isn't working.  Could someone please help fix this problem?
    Message was edited by: shawn234

    Oops, the mainVars was a typo.
    What I want to have as the finished product is a video page of multiple video players, each player with a different mainVar value.  The mainVar would tell the videoArray what to change the simplified videoTitle and videoFile variables to.
    That's the plan.  I don't know how to impliment it.  I figured an array would be a good choice since the array can have infinite "i" values, but I could be horribly wrong...

  • Array Loop saying NullPointer

    Excuse my rough coding but here is the method where the problem lies
    public ArrayList<File> dirList(File dir){
            ArrayList<File> dirs = new ArrayList<File>();      
            File[] files = dir.listFiles();
            System.out.println(files.length);
            for(int k = 0; k < files.length; k++){
                int count = 1;
                while(count > 0){
                    int i = 0;
                    count = 0;
                    File[] files2 = files.listFiles();
    boolean isDir = files[i].isDirectory();
    if(isDir){
    dirs.add(files[k]);
    count++;
    screen.print(files[i].getAbsolutePath());
    i++;
    files = files2;
    return dirs;
    When it hits the for look, it complains about a null point exception on that line. I used a debugger as well as printing it to the terminal that the array has 3 elements that are not null.

    When it hits the for look, it complains about a null
    point exception on that line.That cannot be true, from the non-actual code you posted. The only way a NullPointerException could occur on that line, would be if files == null, and then it would have thrown the exception on the preceding line:
    System.out.println(files.length);
    So let's not show some fake code which doesn't represent the real mccoy.

  • Please check this out, It is array loop question

    Question is given main class which is
    import java.util.Scanner;
    public class PascalDriver{
    public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter number of rows");
    int rowCount = scan.nextInt();
    PascalTri t = new PascalTri(rowCount);
    t.displayRows();
    then ask me to right a class which is named PascalTri
    that is what I get:
    public class PascalTri {
    int triangle[][]=new int[rows][rows];
    for(int i=0;i<rows;i++){
    for(int j=0;j<rows;j++){
    triangle[i][j]=0;
    triangle[0][0]=1;
    triangle[1][0]=1;
    triangle[1][1]=1;
    for(int i=2;i<rows;i++){
    triangle[0]=1;
    for(int j=1;j<=i;j++){
    triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
    public displayRows(){
    return triangle[i][j];
    is it right? I donot know y dr.java says "for(int i=0;i<rows;i++){ "is an error, I donot know y, can anyone help me?

    public class PascalTri {
    private int triangle[][];
    private int rows;
    public PascalTri(int numRows){
    rows = numRows;
    int triangle[][]=new int[rows][rows];
    for(int i=0;i<rows;i++){
    for(int j=0;j<rows;j++){
    triangle[i][j]=0;
    triangle[0][0]=1;
    triangle[1][0]=1;
    triangle[1][1]=1;
    for(int i=2;i<rows;i++){
    triangle[0]=1;
    for(int j=1;j<=i;j++){
    triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
    public void displayRows(){
    System.out.println(triangle[i][j]);
    }I am a foreign student, maybe I donot understand what you mean clearly. But I think my code is right, it all makes sence. then value will get into construct and  I really think this is right.... Can you tell me where is my error?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Looping Array of Netstream .flv videos

    I have so far been successful getting my array of dynamically
    loaded videos to stitch together and play using the code below. My
    first question is how do I tell the .swf to start playing the first
    movie in the array upon completion of the last movie in the array
    (loop array). I assume this is some sort of onComplete event, but
    I'm not sure how to tie it into the below:
    My second question is what is the best way to begin
    pre-loading these movies from an 'Enter' page so that they buffer
    and run more smoothly? I assume that if I can manage this better, I
    will be able to use the higher-quality .flv files for optimal
    viewing.
    I appreciate any insight that can be offered.
    Thanks,
    Chuck

    That worked well to get the array to loop back to the first
    movie, but now it wants to stop after the the first .flv in the
    array completes after the loop is initiated. Any ideas?
    Link to issue
    example
    Thanks again,
    Chuck

  • Arrays to lists in db or something better?

    I have a form that is dynamic in that it first asks the user
    how many entries they will be making. If the user says 5, an array
    is created to accomodate that such as
    <cfset SESSION.newarray = structNew(2)>
    The form is generated using a cfloop to create the rows in
    accordance with the number of entries requested.
    I don't want to put these values into a list and into the
    database, but the user can request up to 20 rows. In this case the
    user is asked how many new customers he wishes to add to the
    database, then the next page creates the array, loops through the
    <cfinput> lines and creates the table. THe results of the
    form is then stored into session variables, so that the user can go
    back and forth through the forms without losing data, and not
    requiring a database read/write each time, until the end. THen the
    data from the array is fed into the database for storage.
    My question (finally!) is this: Is it more effecient to
    create 20 columns in the database to store each of the possible
    entries, or create a list and store the data in lists, pulling the
    lists out and finding data from the lists or is there a better way?
    Thanks.

    A better way would be to store 20 records. Sounds like a
    course in data modelling would benefit you.

  • I have a Build Array function within a case structure. This array gets populated properly but I am unable to pass this array out of the case structure.

    I'm including a .png file that shows how I've coded this array.  This is part of a subvi.  Do arrays/loops behave differently in subvi's than in vi's?
    Attachments:
    arrays and loops.png ‏29 KB

    Can you attach your actual VI?
    I think there are a few more problem areas, for example:
    Why are you reading "time Stamp 3" from a value property node with each iteration of the loop? Due to the speed of the loop is very unlikely that that value changes between iterations (and if it would, it would give unpredictable results!). Thus you should read that value once before the loop or better just wire from the actual terminal. Property nodes force synchronous execution and are several orders of magnitude slower than any other method of data transfer.
    LabVIEW Champion . Do more with less code and in less time .

  • How to use XSLT for mapping feild names one by one to array element

    I have a XSLT case to map all the attributes feild name(not value) which has no child to the target, which is array loop.
    I give an sample below.
    source:
    <Items xmlns="http://www.example.org/sample">
    <SourceSystem>SourceSystem2573</SourceSystem>
    <TimeStamp>2010-01-17T20:54:08.234</TimeStamp>
    <Item>
    <ID>2574</ID>
    <Type>2575</Type>
    <Name>2576</Name>
    </Item>
    </Items>
    source XSD like:
         <element name="Items" type="tns:ItemsType"></element>
         <complexType name="ItemsType">
              <sequence>
                   <element name="SourceSystem" type="string" maxOccurs="1"
                        minOccurs="1">
                   </element>
                   <element name="TimeStamp" type="dateTime" maxOccurs="1"
                        minOccurs="1">
                   </element>
                   <element name="Item" type="tns:ItemType"
                        maxOccurs="unbounded" minOccurs="1">
                   </element>
    </sequence>
         </complexType>
    <complexType name="ItemType">
              <sequence>
                   <element name="ID" type="string" maxOccurs="1"
                        minOccurs="1">
                   </element>
                   <element name="Type" type="string" maxOccurs="1"
                        minOccurs="1">
                   </element>
    <element name="Name" type="string" maxOccurs="1"
                        minOccurs="1">
                   </element>
    </sequence>
         </complexType>
    target need to be like:
    <ns1:AttributesCollection>
    <ns1:Attributes>
    <ns1:fieldname>SourceSystem</ns1:fieldname>
    </ns1:Attributes>
    <ns1:Attributes>
    <ns1:fieldname>TimeStamp</ns1:fieldname>
    </ns1:Attributes>
    <ns1:Attributes>
    <ns1:fieldname>ID</ns1:fieldname>
    </ns1:Attributes>
    <ns1:Attributes>
    <ns1:fieldname>Type</ns1:fieldname>
    </ns1:Attributes>
    <ns1:Attributes>
    <ns1:fieldname>Name</ns1:fieldname>
    </ns1:Attributes>
    </ns1:AttributesCollection>
    target XSD:
    <xs:element name="AttributesCollection" type="AttributesCollection"/>
    <xs:complexType name="AttributesCollection">
    <xs:sequence>
    <xs:element name="Attributes" type="Attributes" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="Attributes">
    <xs:sequence>
    <xs:element name="fieldname" minOccurs="0">
    <xs:simpleType>
    <xs:restriction base="xs:string">
    <xs:maxLength value="100"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:element>
    </xs:sequence>
    </xs:complexType>
    I know we can use local-name() to get the tag/field name,
    but I have not idea how to get these leaf field names one by one and then mapping to every array elements.
    I tried whole day but no successful
    Does anyone have some idea?
    Thanks very much!
    Keith
    Edited by: user1065212 on 17-Jan-2010 22:50
    Edited by: user1065212 on 17-Jan-2010 22:53
    Edited by: user1065212 on 17-Jan-2010 22:59

    can you paste source xsd and the correct xml output, the current one isn't really valid
    <ID>2574</TotalNumOfItems>

  • How can I load the data of Manager Beans into an Array?

    Hi all!
    I have a problem when use the ADF model layer (JDeveloper 10g). I want to load the data of a Manager Bean into Array(such as: Array in JavaScript).But I don't know any ways to do.
    Are there any ways to do that?
    Please, help me!
    Thanks so much!

    Hi,
    there is a fundamental difference between an array in Java and an array in JavaScript as the latter is added to the output page while the first sits in a Java class on the server.
    Populating a Java array from a managed bean is straight froward: Just create the Array, loop through the source of the data - ADF binding or the ADF Faces table component - and fill it.
    For a JavaScript Array I would suggest to write the array into a js file and reference it from the web page (which might cause concurrency issues).
    Frank

  • Printing a listing from an array of objects

    I know I'm missing something simple here but for the life of me I can't spot it. The code below should print a list of student names to the screen. At the moment it only prints the last name entered into the array. I will kick myself when I see the answer but can anyone suss this out ? Many thanks for any help.
    // A Program called StudentDetails3.java which inserts student names into an array according to
    // a calculated hash Index and then prints out the name list in this order
    import javax.swing.JOptionPane;
    public class StudentDetails3
    // Member Section
    // Private members
    private static String studentName;
    // Public members
    public static String input = JOptionPane.showInputDialog(" Please enter the number of students in the class : - ");
    public static int maxNum = Integer.parseInt(input);
    public static int hashIndex = 0;
    // Constructor Section
    StudentDetails3 ( String newStudentName )
    studentName = newStudentName.toUpperCase();
    // Method Section
    public int hashCalc()
    int total = 0;
    for( int charNo = 0; charNo < studentName.length(); charNo ++ )
    char letter = studentName.charAt(charNo);
    int asciiVal = letter;
         if( studentName.charAt(charNo) ==' ')
         asciiVal = 0;
         total = total + asciiVal;
    hashIndex = total % maxNum;
    return hashIndex;
    public void output()
    System.out.println(" The student's name and hash index is " + studentName + " " + hashIndex );
    static class DetailsStorage
    // Member Section containing the array into which the student objects will be inserted
    private Object [] array;
    private int current;
    // Constructor
    DetailsStorage ( int noOfStudents )
    array = new Object[ noOfStudents ];
    current = 0;
    // Method for adding name to array
    public void add ( Object StudentDetails3 )
    {  if ( array [ hashIndex] == null )
    array [ hashIndex ] = StudentDetails3;
    else if ( (hashIndex + 1) <= (array.length-1) )
    do
    { hashIndex = ( hashIndex + 1 );
         if ( array [ hashIndex ] == null )
         {   array [ hashIndex ] = StudentDetails3;
         break;
    } while ( (hashIndex + 1) <= (array.length-1) );
         else
              for ( int firstLp = 0; firstLp < array.length; firstLp ++ )
         if ( array [ firstLp ] == null )
         {   array [ firstLp ] = StudentDetails3;
                   break;
    public void printOut ( )
    {   int loop = 0;
    System.out.println ( " Name\t\tCourse " );
    System.out.println ( "____\t\t_________ " );
         for ( loop = 0; loop < array.length; loop ++ )
         System.out.println ( ( ( StudentDetails3 ) array [ loop ] ).studentName );
    // Main Program for testing
    public static void main( String[] args )
    {   String  name;                                              
    // Obtain list of names from the user
    DetailsStorage nameList = new DetailsStorage( maxNum );
    for( int lp = 0; lp < maxNum; lp++ )
    {   name =  JOptionPane.showInputDialog(" Please enter the name of student in full ( e.g. Gareth Edwards )");
    StudentDetails3 newDetails = new StudentDetails3( name );
    newDetails.hashCalc();
         nameList.add ( newDetails );
    newDetails.output();
    nameList.printOut();
    System.exit(0);
    }

    You've made the student name a static field, which means that there's only one for the whole class.
    So the last one you input is the one you use for everybody.

  • Hi all, i need Help in Arrays

    Hi All,
    I have some problems on the below questions scenario;
    Program 1
    You are to write a program using a method other than main. The program is to
    �     collect monthly rainfall figures for 12 months
    �     pass the total annual rainfall to another method which calculates the average monthly rainfall and returns it to the main method
    �     calculate the variation of each month from the average (as a positive)
    �     display the results
    Sample input screen
    Enter rainfall for month 1:     13.3
    Enter rainfall for month 2:      14.9
    Enter rainfall for month 3:      14.7
    Enter rainfall for month 4:      23.0
    etc for the 12 months jan-dec
    After the 12 months of data has been collected as report as follows is displayed:
    Annual Rainfall Report
    Monthly average: 15.04mm
    Month          Rainfall     Variation
    January          13.3          1.73
    February          14.9          0.13
    March          14.7          0.33
    April          23.0          7.97
    etc for the year�
    Problem 2
    You are to make major improvements to last week�s program.
    The format of your program and some key elements should be as follows:
    public class Rainfall
         public static void main()
              Create an array for monthly rainfall
              Loop to collect rainfall figures from user and store in array
              Loop through rainfall array
                   Call printRainfall method passing month number, rainfall for                          that month, and average as parameters
         printRainfall method
              Create an initialiser list array of month names
                   (ie hard code the month names in your program)
              Print report headings
              Use the parameters to access month names array and print report                          detail line
    I have problems with the Problem 2 which i can't loop up the input values and printouts using aarays to do it.
    Can anyone out there help me to solve the problems ? If possible, please reply me at my email @ [email protected] .Lotsa thanks.
    Thanks and Regards.

    So why don't you tell us exactly what's going wrong and show us the code where it's going wrong.

Maybe you are looking for

  • Help required - transfering music files

    Can anyone help? I had about 1000 songs on my laptop which I put onto my ipod - the transfer method was via real player. The transfer appeared succesful and the music is on my ipod. However I cant play it - and now I've deleted it from my hard drive.

  • HT204023 Personal Hotspot: Which is better? Wifi Vs Bluetooth (or both together)

    Hi, If i'm using my iPhone to share internet with my iPad using personal hotspot. Is Wi-Fi better than bluetooth as a sharing option or should I use both solutions together? How does each solution afect my internet speed? Thanks.

  • What error is this ?

    Hi all ,i need your help . I just got this error message when i wan to select column of my database. NI_Database_API.lvlib:Conn Execute.vi->NI_Database_API.lvlibB Tools Select Data.vi->FYP.vi<ERR>ADO Error: 0x80040E14 Exception occured in Microsoft O

  • DEBMAS with only part of contact persons?

    Hi there, if we send in a DEBMAS IDoc that contains only a subset of contact persons of a customer, the inbound process will remove all other contact records from KNVK. We tried different MSGFN values, without success. Is there any way we could send

  • BAPI_GOODSMVT_CREATE lock issue with no access to ABAP!

    Hello everyone, I have written a class in vb .NET that uses the BAPI_GOODSMVT_CREATE to post goods issues. I have done numerous tests myself which all were successful. However, when a colleague wanted to test my class he suddenly got the following er