Unit 8
Unit 8
2D Arrays are a lot like arrays, but have an extra index which makes them 2D instead of 1D
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 Array = a data structure used to implement a collection (list) of primitive or object reference data Is public, so can be accessed in any class
A 2D array is an array of arrays, and can be a better way to store data
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!
}
}
Test.main(null);
You can use Nested Loops to traverse 2D Arrays for example: to print out an entire array in order, you need to use these
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
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);
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];
for(int row = 0; row < arr.length; row++) {
for(int column = 0; column < arr[row].length; column++) {
if (arr[row][column].length() > longest.length()) {
longest = arr[row][column];
}
}
}
System.out.println(longest);
// 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!");
}
}
Test.main(null);
To create a two dimensional array in Java, you have to specify the data type of items to be stored in the array, followed by two square brackets and the name of the array.
import java.util.*;
class Tree {
private String [][] tree;
public Tree () {
tree = new String[][]{ //2D array above is just a name, "new" makes a container ("object")
{ " * " },
{ " *** " },
{ " ***** " },
{ " ******* " },
{ " ********* " },
{ " *********** " },
{ "************* " },
{ " || " },
{ " || " }
};
}
public void printASCII () {
for (int row = 0; row < tree.length;row++) {
for (int column = 0; column < tree[row].length; column++) {
System.out.println(tree[row][column]);
}
}
}
}
Tree myTree = new Tree();
myTree.printASCII();