Learning Objective!

2D Array Vocab:

  • Array = a data structure used to implement a collection (list) of primitive or object reference data
  • Element = a single value in the array
  • Index = the position of the element in the array (starts from 0)
  • Array Length = the number of elements in the array
    • Is public, so can be accessed in any class
    • Is also final, so can’t change it after array has been created

The Basics:

  • A 2D array is an array of arrays, and can be a better way to store data
  • Declaring a 2D array:
    • DataType[][] nameOf2DArray
  • Initializing a 2D array
    • DataType[][] nameOf2DArray = new DataType[r][c];
      • r = # of rows
        • The # of arrays in the array
        • r = list.length
          • c = # of columns
        • The # of elements in the inner arrays
        • c = list[0].length

Initializing a Sample Array:

public class Test {

   public static void main(String[] args) {

      int[][] arr = {
         { 1, 2, 3 },
         { 4, 5, 6 },
         { 7, 8, 9 }
      };

      System.out.println("arr[0][0] = " + arr[0][0]);
      System.out.println("arr[1][2] = " + arr[1][2]);
      System.out.println("arr[2][1] = " + arr[2][1]);
      
   }

}
Test.main(null);
arr[0][0] = 1
arr[2][0] = 6
arr[2][1] = 8

Accessing and Updating Elements of a 2D Array:

  • nameOf2DArray[r][c]

Hack 1: Access the last element of the 2D Array list:

public class Test {

    public static void main(String[] args) {
 
      String[][] arr = {
         { "a", "f", "g" },
         { "b", "e", "h" },
         { "c", "d", "i" }
      };
 
      // Print the last element in the array!

      System.out.println(arr[2][2]);
       
    }
 
 }
 Test.main(null);
i
  • a quick tip for the future: list[list.length - 1][list[0].length - 1]
  • Updating an element:
    • list[r][c] = value;

Hack 2: Changing a Value:

public class Test {

    public static void main(String[] args) {
 
      String[][] arr = {
         { "Atlanta", "Baltimore", "Chicago" },
         { "Australia", "Boston", "Cincinnati" },
         { "Austin", "Beaumont", "Columbus" }
      };
 
       // Change Austin to Athens and print!
       System.out.println("Change Austin to Athens and print!");
       
       arr[2][0] = "Athens";

       System.out.println(arr);
    }
 
 }
 Test.main(null);
Change Austin to Athens and print!
[[Ljava.lang.String;@134856d2

Nested Loops, Our Beloved:

  • You can use Nested Loops to traverse 2D Arrays
    • for example: to print out an entire array in order, you need to use these
public class Test {

    public static void main(String[] args) {
 
      String[][] arr = {
         { "a", "f", "g", "l" },
         { "b", "e", "h", "k" },
         { "c", "d", "i", "j" }
      };
 
      for (int row = 0; row < 3; row++) {
         for (int col = 0; col < 4; col++) {
            System.out.print(arr[row][col] + " ");
         }
        System.out.println(" ");
      }
       
    }
 
 }
 Test.main(null);
a f g l  
b e h k  
c d i j  
  • Make sure your columns for loop is always inside your rows for loop!
    • Unless you want it printed the other way of course
  • Print spaces and lines in between to make a neater matrix

Hack 3: Unknown Dimensions:

public class Test {

   public static void main(String[] args) {

      String[][] arr = {
         { "Atlanta", "Baltimore", "Chicago" },
         { "Australia", "Boston", "Cincinnati" },
         { "Austin", "Beaumont", "Columbus" }
      };

      // Print out the array without using numerical values!
      for (String[] row : arr) {
         for (String place : row) {
            System.out.print(place + " ");
         }
         System.out.println();
      }
      
   }

}
Test.main(null);
Atlanta Baltimore Chicago 
Australia Boston Cincinnati 
Austin Beaumont Columbus 

Searching for a Value in a 2D Array:

  • Here's a quick example to illustrate:
public class Test {

    public static void main(String[] args) {
  
        String[][] arr = {
            { "Atlanta", "Baltimore", "Chicago" },
            { "Australia", "Boston", "Cincinnati" },
            { "Austin", "Beaumont", "Columbus" }
        };

        String match = "";
        String name = "Boston";
        for (String[] row : arr) {
            for (String item : row) {
                if (item.equals(name)) {
                    match = name;
                }
            }
        }

        if (match.length() == 0) {
            System.out.println("No Match!");
        } else {
            System.out.println(name);
        }
        
    }
 
 }
Test.main(null);
Boston
  • Note: in the code, you see the use of : which essentially means within.

Hack 4: Finding the Min/Max Value:

public class Test {

    public static void main(String[] args) {
  
        String[][] arr = {
            { "Atlanta", "Baltimore", "Chicago" },
            { "Australia", "Boston", "Cincinnati" },
            { "Austin", "Beaumont", "Columbus" }
        };

        String longest = arr[0][0];

        // Use nested for loops to find the longest or shortest string!
        System.out.println("Use nested for loops to find the longest or shortest string!");

        for (String[] row : arr) {
            for (String place : row) {
                if (place.length() > longest.length()) {
                    longest = place;
                }
            }
        }

        System.out.println(longest);
        
    }
 
 }
Test.main(null);
Use nested for loops to find the longest or shortest string!
Cincinnati

HW!

Additionally, Complete and send a screenshot of your code for 2017 FRQ Q4: Successor Array in that same google form.

Please submit as a pair or group.

public class Position {

    public static int[][] array = {
        {15, 5, 9, 10}, 
        {12, 16, 11, 6}, 
        {14, 8, 13, 7}
    };

    private int row;
    private int col;

    public Position(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public String getPosition() {
        if (this != null) {
            return "[" + this.row + ", " + this.col + "]";
        } else {
            return "value does not exist in the array";
        }
    }

    public static Position findPosition(int value, int[][] array) {

        for (int row = 0; row < array.length; row++) {
            for (int col = 0; col < array[0].length; col++) {
                if (value == array[row][col]) {
                    return new Position(row, col);
                }
            }
        }

        return null;

    }

    public static void main(String[] args) {

        if (findPosition(8, array) != null) {
            System.out.println(findPosition(8, array).getPosition());   
        }

        if (findPosition(17, array) != null) {
            System.out.println(findPosition(17, array).getPosition());
        } else {
            System.out.println("integer is not in array");
        }

    }

}

Position.main(null);
[2, 1]
integer is not in array
public class Successors {

    public static Position[][] getSuccessorArray(int[][] intArr) {
        
        Position[][] posArr = new Position[3][4];

        for (int row = 0; row < intArr.length; row++) {
            for (int col = 0; col < intArr[0].length; col++) {
                
                int newNum = intArr[row][col] + 1;
                Position position = Position.findPosition(newNum, intArr);

                posArr[row][col] = position;

            }
        }

        return posArr;
    }

    public static String[][] successorArrayToStringArray(Position[][] successorArr) {
        
        String[][] stringArr = new String[3][4];
        
        for (int row = 0; row < successorArr.length; row++) {
            for (int col = 0; col < successorArr[0].length; col++) {
                if (successorArr[row][col] != null) {
                    stringArr[row][col] = successorArr[row][col].getPosition();
                } else {
                    stringArr[row][col] = null;
                }
            }
        }
        
        return stringArr;
    }

    public static void printSuccessorArray(String[][] stringArr) {

        for (String[] row : stringArr) {
            for (String col : row) {
                System.out.print(col + "  ");
            }
            System.out.println();
        }

    }

    public static void main(String[] args) {

        printSuccessorArray(successorArrayToStringArray(getSuccessorArray(Position.array)));

    }
}

Successors.main(null);
[1, 1]  [1, 3]  [0, 3]  [1, 2]  
[2, 2]  null  [1, 0]  [2, 3]  
[0, 0]  [0, 2]  [2, 0]  [2, 1]  
public class Tree {

    public static void printTree(int length) {
        for (int row = 0; row < length; row++) {
            for (int spaces = length-row; spaces > 0; spaces--) {
                System.out.format(" ");
            }
            for (int astericks = 0; astericks <= row; astericks++) {
                System.out.print("* ");
            }
            for (int spaces = length-row; spaces > 0; spaces--) {
                System.out.print(" ");
            }
            System.out.println();
        }

        for (int trunkRows = length / 5; trunkRows >= 0; trunkRows--) {
            for (int spaces = length/2; spaces >= -1; spaces--) {
                System.out.print(" ");
            }
            System.out.print("||");
            System.out.println();   
        }
    }

    public static void main(String[] args) {
        printTree(6);
    }
}

Tree.main(null);
      *       
     * *      
    * * *     
   * * * *    
  * * * * *   
 * * * * * *  
     ||
     ||