![]() |
Home | Methods & Control Structures | Class Implementation | Arrays/ArrayLists | 2D Arrays |
Question 3 — 2D Arrays
Notes on FRQ Question
Creation of 2D Array
// Declare a 2D array
int[][] array = new int[3][4]; // 3 rows and 4 columns
// Declare and initialize with values
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Indexing 2D Arrays
To index a 2D array, place the row number, followed by the column number.
// Access elements in the array
int value = array[0][1]; // Gets the number in the 1st row and 2nd column
System.out.println(value); // Output: 2
int value2 = array[1][2]; // Gets the number in the 2nd row and 3rd column
System.out.println(value2); // Output: 6
// Whoopsie daisies! Error! This is out of bounds
int value3 = array[20][10];
System.out.println(value3);
Iteration of 2D Array
To iterate through a 2D array:
Row-major order
// For loop: Add 5 to all elements of the array
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
array[row][col] += 5; // Add 5 to each element
}
}
// Foreach loop: Output all elements of the array
for (int[] row : array) {
for (int item : row) {
System.out.print(item + " ");
}
System.out.println(); // Adds a newline after each row
}
Column-major order
for (int col = 0; col < array[0].length; col++) {
for (int row = 0; row < array.length; row++) {
System.out.print(array[row][col]);
}
System.out.println();
}
Example - 2020 FRQ Part 4
public class Seat {
private boolean available;
private int tier;
public Seat(boolean isAvail, int tierNum) {
available = isAvail;
tier = tierNum;
}
public boolean isAvailable() {
return available;
}
public int getTier() {
return tier;
}
public void setAvailability(boolean isAvail) {
available = isAvail;
}
}
public class Theater {
private Seat[][] theaterSeats;
public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) {
this.theaterSeats = new Seat[tier1Rows + tier2Rows][seatsPerRow];
}
public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) {
Seat fromSeat = theaterSeats[fromRow][fromCol];
Seat toSeat = theaterSeats[toRow][toCol];
if (fromSeat.getTier() < toSeat.getTier() || !toSeat.isAvailable()) {
return false;
}
theaterSeats[fromRow][fromCol] = toSeat;
theaterSeats[toRow][toCol] = fromSeat;
return true;
}
}