12-02-2013

posted Dec 3, 2013, 5:27 AM by Samuel Konstantinovich   [ updated Dec 3, 2013, 5:30 AM ]
2D ARRAY SAMPLE CODE:

    /*Fill a 2d array with random integers*/
    public static void fill(int[][]L){
        for(int i = 0; i < L.length; i++){
            for(int j = 0; j < L[i].length; j++){
                L[i][j]= (int)(Math.random()*100);
            }
        }
    }

    /*TAKE NOTE OF HOW PRINT ARRAY WORKS!*/
    public static void printArray(int[]L){
        System.out.print("[");
        for(int i = 0; i< L.length; i++){
            System.out.print(L[i]+" ");
        }
        System.out.println("]");
    }
    public static void printArray(int[][]L){
        System.out.println("[");
        for(int i = 0; i< L.length; i++){
            printArray(L[i]);
        }
        System.out.println("]");
    }
    public static void main(String[]args){
        /*first way to initialize a 2d array*/
        String[][]LST = new String[10][8];/*both dimensions are filled in*/

        /* second way to initialize a 2d array*/
        /*initialize the 1st array, 
          but leave the inner arrays blank*/
        int [][]L = new int[2][];
        /*initialize each individual inner array, 
          this can be done with a loop*/
        L[0] = new int[7];
        L[1] = new int[10];
        fill(L);
        printArray(L);
        System.out.println();
        /*setting L[0] to L[1] makes L[0] point 
          to the same address*/
        L[0] = L[1];
        printArray(L);
        System.out.println();
        L[0][0]=999;/*this changes both L[0] and L[1]..*/
        printArray(L);
        System.out.println();
    }

Comments