import java.util.Scanner;
class ExceptionWrongMatrixDimension extends Exception {
public ExceptionWrongMatrixDimension(String str)
{
super(str);
}
}
class twoDimensionalMatrix {
void Matrix(int n, int m)
throws ExceptionWrongMatrixDimension
{
int[][] matrix = { { 1, 2 },
{
4,
5,
} };
System.out.println("\nMatrix is :");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
int rows = 2;
int cols = 2;
if (n != rows) {
throw new ExceptionWrongMatrixDimension(
"Invalid matrix dimensions to multiply");
}
else {
int[][] m_matrix = { { 6, 3 },
{
9,
2,
} };
System.out.println("\nMatrix to multiply is :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(m_matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\nMatrix to multiply is :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(m_matrix[i][j] + " ");
}
System.out.println();
}
int c[][] = new int[m][n];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
c[i][j] = 0;
for (int k = 0; k < rows; k++) {
c[i][j] += matrix[i][j]
* m_matrix[k][j];
}
}
}
System.out.println(
"\n\nMatrix after multiplication is");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
}
public class Main {
public static void main(String args[])
{
twoDimensionalMatrix matrix
= new twoDimensionalMatrix();
try {
System.out.println("Enter the number of rows");
int n = 2;
System.out.println(
"Enter the number of columns");
int m = 2;
matrix.Matrix(n, m);
}
catch (ExceptionWrongMatrixDimension e) {
System.out.println(
"ExceptionWrongMatrixDimension:");
System.out.println(e.getMessage());
}
}
}