A class Shift contains a two-dimensional integer array of order (m × n) where the maximum values of both m and n is 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 members/instance variables:
mat[][]: stores the array elements
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.
import java.util.Scanner;
class Shift{
int mat[][];
int m;
int n;
public Shift(int mm, int nn){
m = mm;
n = nn;
if(m > 5)
m = 5;
if(n > 5)
n = 5;
mat = new int[m][n];
}
public void input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter matrix elements:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mat[i][j] = Integer.parseInt(in.nextLine());
}
}
}
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){
Scanner in = new Scanner(System.in);
System.out.print("Number of rows: ");
int rows = Integer.parseInt(in.nextLine());
System.out.print("Number of columns: ");
int cols = Integer.parseInt(in.nextLine());
Shift x = new Shift(rows, cols);
x.input();
System.out.println("Original Matrix");
x.display();
Shift y = new Shift(rows, cols);
y.cyclic(x);
System.out.println("New Matrix");
y.display();
}
}