Unit 8: 2D Arrays
Homework
- Create a class for 2D array learning.
- Create a method to initialize a 2D array with arbitrary values
- Create a method to reverse the 2D array and print out the values
- Create a method that asks for the input of a position and it returns the corresponding value
- Create a method that multiplies each value in a row and then adds all the products together
- Create a new object to test out each method in the main function
import java.util.Scanner;
import java.util.Random;
public class Homework {
int[][] numbers;
public void printValues() { // arbitrary values
for (int a = 0; a<numbers.length; a++) {
for (int b = 0; b<numbers[a].length; b++) {
numbers[a][b] = a + b; // spacing
System.out.println(numbers[a][b] + " "); // spacing
}
System.out.println();
}
}
public void reverseValues() {
for (int a = numbers.length-1; a >= 0; a--) { // running for loop from ends of array
for (int b = numbers[a].length-1; b >= 0; b--) {
System.out.println(numbers[a][b] + " ");
}
System.out.println();
}
}
public void findPosition() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input row (0-2): ");
int a = scanner.nextInt();
System.out.println("Input column (0-2): ");
int b = scanner.nextInt();
System.out.println(numbers[a][b]);
}
public void mathNumbers() {
int total = 0;
for (int a = 0; a < numbers.length; a++) {
int product = 1;
for (int b = 0; b <numbers[a].length; b++) { // product of row
product = product * numbers[a][b];
}
total += product;
}
System.out.println("Sum of row products: " + total);
}
public static void main(String[] args) {
Homework homework = new Homework();
homework.printValues();
homework.reverseValues();
homework.findPosition();
homework.mathNumbers();
}
}
Homework.main(null);