2D Arrays

  • Array of arrays
  • Can be initialized using [][] (double brackets)
  • Two for loops can be used to traverse through each row and then each column in the 2d array
  • Specify index by row and column to access 2d array (like a matrix
  • Change how you print and display them according to row/column and iterate through them in different ways to go through them

2D Array HW

import java.util.Scanner;

public class Arrays{
    int[][] numbers;
    public Arrays(){
        int[][] newArray = new int[4][4];;
        for (int i = 0; i < newArray.length; i++){
            for (int j = 0; j < newArray[i].length; j++){
                newArray[i][j] = (j+1) * (int) (Math.random()*10);
            }
        }

        this.numbers = newArray;
    }

    public void printArray(){
        for(int i = 0; i < numbers.length; i++){
            for(int j = 0; j < numbers[i].length; j++){
                System.out.print(numbers[i][j] + " ");
            }

            System.out.println();

        }
    }

    public void reverseArray(){
        System.out.println("\n\nPrinting out values backward");
        for(int i = numbers.length-1;i>=0;i--){
            for(int j = numbers[i].length-1; j >= 0;j--){ 
                System.out.print(numbers[i][j] + " ");
            }
            System.out.println(" ");
        }
    }

    public void askForIndex(){
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Row Index: ");
        int rowIndex = scanner.nextInt();
        System.out.println(rowIndex);

        System.out.print("Enter Column Index: ");
        int columnIndex = scanner.nextInt();
        System.out.println(columnIndex);

        System.out.print("Result: "); 
        System.out.println(numbers[rowIndex][columnIndex]);
    }

    public void multiplyThenSum(){
        int sum = 0;

        for(int i = 0; i < numbers.length; i++){
            int multiply = 1;

            for(int j = 0; j < numbers[i].length; j++){
                multiply *= numbers[i][j];
            }

            sum += multiply;
        }

        System.out.print("Sum: ");
        System.out.println(sum);
    }

    public static void main(String[] args){
        Arrays array = new Arrays();
        array.printArray();
        array.reverseArray();
        array.askForIndex();
        array.multiplyThenSum();

    }
}

Arrays.main(null);
7 10 21 0 
9 16 0 8 
6 10 18 36 
2 6 12 16 


Printing out values backward
16 12 6 2  
36 18 10 6  
8 0 16 9  
0 21 10 7  
Enter Row Index: 0
Enter Column Index: 0
Result: 7
Sum: 41184