Unit 8 - 2D Array HW
2D array hacks
public class TwoDArray {
private int[][] array;
// constructor to initialize values of array
public TwoDArray(int[][] array) {
this.array = array;
}
// reverse rows and print it out
public void reverse() {
System.out.println("Reversed: ");
int[][] newArray = new int[this.array.length][this.array[0].length];
for(int i = this.array.length-1; i >= 0; i--) {
for(int j = 0; j<this.array[i].length; j++) {
System.out.println(this.array[i][j] + " ");
};
};
System.out.println(" ");
}
// get value at column
public void getValue(int row, int column) {
System.out.println("Value at (" + row + "," + column + "): " + this.array[row][column]);
}
// add products of rows
public void addProducts() {
int sum = 0;
for(int i = 0; i<this.array.length; i++) {
int product = 1;
for(int j = 0; j<this.array[i].length; j++) {
product *= array[i][j];
}
sum += product;
}
System.out.println("Sum of products of rows: " + sum);
}
// tester method
public static void main(String [] args) {
int[][] newArray = {{0, 1}, {2, 3}};
TwoDArray array = new TwoDArray(newArray);
array.getValue(0,1);
array.reverse();
array.addProducts();
}
}
TwoDArray.main(null);