Answers for 2D Arrays
Answers for 2D Array Lesson
Popcorn Hack 1
import java.util.Random;
public class Random2DArray {
public static void main(String[] args) {
int numRows = 4; // Change this to the desired number of rows
int numCols = 4; // Change this to the desired number of columns
int[][] randomArray = new int[numRows][numCols];
Random random = new Random();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
randomArray[i][j] = random.nextInt(100); // Generates random integers between 0 and 99
}
}
// Print the random 2D array
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(randomArray[i][j] + " ");
}
System.out.println(); // Move to the next row
}
}
}
Popcorn Hack 2
public class Main {
public static void main(String[] args) {
int[][] myArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int desiredVal = 12;
myArray[2][2] = 12;
System.out.print(myArray[2][2]);
}
}
Main.main(null)
12
Popcorn Hack 3
public class Main {
public static void main(String[] args) {
int[][] myArray = {
{1, 2, 11},
{14, 5, 21},
{25, 28, 70}
};
for (int i = 0; i < myArray.length; i++) { // Loop through the rows
for (int j = 0; j < myArray[i].length; j++) { // Loop through the columns
int x = myArray[i][j];
if(x %7 == 0){
System.out.print(myArray[i][j] + " "); // Print out the element
}
}
System.out.println(); // Print a new line
}
}
}
Main.main(null)
14 21
28 70