InterviewSolution
| 1. |
A class Shift contains a two-dimensional integer array of order (m×n) where the maximum values of both m and n are 5. Design the class Shift to shuffle the matrix (i.e. the first row becomes the last, the second row becomes the first and so on). The details of the members of the class are given below:Class name: Shift Data member/instance variable: mat[][]: stores the array element m: integer to store the number of rows n: integer to store the number of columns Member functions/methods: Shift(int mm, int nn): parameterized constructor to initialize the data members m=mm and n=nn void input(): enters the elements of the array void cyclic(Shift p): enables the matrix of the object (P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object void display(): displays the matrix elements Specify the class Shift giving details of the constructor(), void input(), void cyclic(Shift) and void display(). Define the main() function to create an object and call the methods accordingly to enable the task of shifting the array elements. |
|
Answer» import java.io.*; class Shift { intmat[][]; int m; int n; public Shift(int mm, int nn){ m = mm; n = nn; m = 5; n = 5; mat = new int[m][n]; } public void input()throws IOException { InputStreamReader input = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(input); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { System.out.print("Elements of the matrix: "+i+", "+j+":"); mat[i] [j] = Integer.parseInt(br.readLine()); } } public void cyclic(Shift p) { for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(i == 0) this.mat[m-1][j] = p.mat[i][j]; else this.mat[i-1][j] = p.mat[i][j]; } } public void display() { for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) System, out .print(mat[i] [j]+" \t"); System.out.println(); } } public static void main(String args[])throws IOException { InputStreamReader input = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(input); System.out.print("M = "); int mm=Integer. parseInt(br.readLine()); System.out.print("N = "); int nn = Integer.parseInt(br.readLine()); Shift obj 1 = new Shift(mm, nn); Shift obj2 = new Shift(mm, nn); obj 1.input(); System.out.println("Original Matrix entered by you :"); obj1.display(); obj2.cyclic(obj1); System.out.println("New Shifted Matrix is :"); obj2.display(); } } |
|