Required Object Class and Driver Class ,Write a Java program to do the following
a) Read two-dimensional array (3 x3)
b) Find the diagonal elements of the array
import java.util.Arrays;
import java.util.Scanner;
class ArrayS{
int[][] arr;
int[] diagFirst, diagSecon;
public ArrayS(int[][] arr) {
this.arr = arr;
this.diagFirst = new int[3];
this.diagSecon = new int[3];
findDiagonals();
}
public void findDiagonals(){
for(int i = 0; i < 3; i++)
diagFirst[i] = arr[i][i];
System.out.println("");
int j = 0;
for(int i = 2; i >= 0; i--){
diagSecon[j] = arr[j][i];
j++;
}
}
@Override
public String toString() {
return "first diagonal " + Arrays.toString(diagFirst) +
"\nsecond diagonal " + Arrays.toString(diagSecon);
}
}
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[][] arr = {{11, 59, 3}, {23, 42, 37}, {1, 2, 3}};
ArrayS obj = new ArrayS(arr);
System.out.println(obj.toString());
}
}
Comments
Leave a comment