Unit 8 2D Array HW - Meena Annamalai
HW for Unit 8
- 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
public class myArray {
private int[][] numbers;
public myArray(){
numbers = new int [5][5];
this.numbers = numbers;
}
public void initializeValues(){
System.out.println("\n\nArray");
Random random = new Random();
for(int i = 0; i < numbers.length;i++){
for(int j = 0; j <numbers[i].length;j++){
numbers[i][j] = random.nextInt(11 - 1) + 1;
System.out.print(numbers[i][j]+" ");
}
System.out.println(" ");
}
}
public void reverseArray() {
System.out.println("\n\nReverse Array");
for(int i = numbers.length-1;i>=0;i--){
for(int j = 0; j <numbers[i].length;j++){
System.out.print(numbers[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("\n");
}
public void outputArrayValue() {
// Create a method that asks for the input of a position and it returns the corresponding value
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter row");
String arrayValue1 = myObj.nextLine(); // Read user input
System.out.println(arrayValue1);
int numArrayValue1 = Integer.parseInt(arrayValue1);
System.out.println("Enter column");
String arrayValue2 = myObj.nextLine(); // Read user input
System.out.println(arrayValue2);
int numArrayValue2 = Integer.parseInt(arrayValue2);
System.out.println("The value in that positions is " + numbers[numArrayValue1][numArrayValue2]);
System.out.println("\n");
}
public void sumOfProducts() {
// Create a method that multiplies each value in a row and then adds all the products together
int finalProduct = 1;
for(int i = 0;i<numbers.length;i++){
int product = 1;
for(int j = 0; j < numbers[i].length;j++){
product = product * numbers[i][j];
}
System.out.print("row " + i + ": product is " + product);
System.out.println(" ");
finalProduct += product;
}
System.out.print("Sum of all products is " + finalProduct);
System.out.println("\n");
}
}
//Create a new object to test out each method in the main function
myArray anArray = new myArray();
anArray.initializeValues();
anArray.reverseArray();
anArray.outputArrayValue();
anArray.sumOfProducts();