Re: macro creating n Arrays within a "for"-loop

Posted by Chris Mawata on
URL: http://imagej.273.s1.nabble.com/macro-creating-n-Arrays-within-a-for-loop-tp3688201p3688209.html

You need an ArrayList<int[ ]>. If the number of arrays is not known
until you are inside the loop
then use a while loop and get out when the number of arrays is the
appropriate number.

Example code ; CreateArrays.java


import java.util.Random;
import java.util.ArrayList;

public class CreateArrays{

     public static void main(String... args){
         Random random = new Random();

         //This will come from some calculation or other
         int numberOfArrays = random.nextInt(10)+1;


         ArrayList<int[]> allArrays = new ArrayList<int[]>();

         for(int i=0; i<numberOfArrays; i++){
             //The size of the ithe array will come from some calculation
             int sizeOfIthArray = random.nextInt(5)+1;
             int[] ithArray=new int[sizeOfIthArray];
             //populate the ith array
             for(int j=0; j< sizeOfIthArray; j++){
                 ithArray[j]=random.nextInt(100);
             }
             //put it int the ArrayList
             allArrays.add(ithArray);
         }

         //Sanity check. If you just need array number i use the syntax
allArrays.get(i).
         System.out.println("We have "+ allArrays.size()+" arrays.\n");
         for(int[] ithArray : allArrays){
             System.out.print("[\t");
             for(int entry : ithArray){
                 System.out.print(entry+"\t");
             }
             System.out.println("]");
         }

     }

}

//end example code

Chris Mawata

On 5/2/2010 10:03 AM, Johannes-Paul M. Koch wrote:

> Dear Listers,
>
> I am trying to create a number of arrays from within a "for"-loop. The
> problem is, that the actual number of arrays depends on something else,
> which means it is not known a priori. And the arrays should be called
> after the loop is finished. So, just to create an array and use it within
> the loop, does not work for me. The best would be to name it, let's say as
> "test" and then add a number for each new array created, test 1, test 2,
> ...
> However, the following did not seem to work....as it seems to redefine the
> string "name"....
>
> for (i=0; i<n; i++) {
>
>       name = "test " +i;
>       name = newArray(k);
>
> }
>
> and this is not accepted anyway...
>
>
>
> for (i=0; i<n; i++) {
>
>       "test " +i = newArray(k);
>
> }
>
>
> Any ideas or workarounds?
>
> Thanks a lot, every help is very much appreciated.
>
> Johannes
>
>