Unit 8 2D Arrays
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!
int row = arr.length - 1;
int col = arr[0].length - 1;
System.out.println(arr[row][col]);
}
}
Test.main(null);
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!
arr[2][0] = "Athens";
System.out.println(arr[2][0]);
}
}
Test.main(null);
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!
int r = arr.length;
int c = arr[0].length;
for (int row = 0; row < r; row++) {
for (int col= 0; col < c; col++){
System.out.print(arr[row][col] + ", " );
}
}
}
}
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];
// Use nested for loops to find the longest or shortest string!
int r = arr.length;
int c = arr[0].length;
for (int row = 0; row < r; row++) {
for (int col= 0; col < c; col++){
if (arr[row][col].length() > longest.length()){
longest = arr[row][col];
}
}
}
System.out.print(longest);
}
}
Test.main(null);
public class Tree {
public static void main(String args[]) {
String[][] tree = {
{" " ," ", " ", "*", " ", " ", " "},
{" ", " ", "*", "*", "*", " ", " "},
{" ", "*", "*", "*", "*", "*", " "},
{"*", "*", "*", "*", "*", "*", "*"},
{" ", " ", " ", "M", " ", " ", " "},
};
int r = tree.length;
int c = tree[0].length;
for (int row = 0; row < r; row++){
for (int col = 0; col < c; col++){
System.out.print(tree[row][col]);
}
System.out.println(" ");
}
}
}
Tree.main(null);