This repository was archived by the owner on Dec 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask7.java
More file actions
76 lines (66 loc) · 1.8 KB
/
Task7.java
File metadata and controls
76 lines (66 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Write a Java program to add two matrices of the same size.
package src.task_7_matrix_add;
import java.util.InputMismatchException;
import java.util.Scanner;
public final class Task7 {
/**
* Size of Matrix.
*/
private static final int SIZE = 5;
private Task7() {
}
/**
* Accepts 5x5 Matrix Input.
*
* @return 5x5 Matrix filled with input values
*/
public static int[][] acceptMatrix() {
int[][] matrix = new int[SIZE][SIZE];
System.out.println("Enter Matrix values: ");
final Scanner inputScan = new Scanner(System.in);
try {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print("Matrix value at " + i + "," + j + ": ");
matrix[i][j] = inputScan.nextInt();
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input");
} finally {
inputScan.close();
}
return matrix;
}
/**
* Adds two 5x5 Matrices and displays them.
*
* @param matrixA
* @param matrixB
*/
public static void addMatrix(final int[][] matrixA, final int[][] matrixB) {
int[][] matrixC = new int[SIZE][SIZE];
System.out.println("Calculating Sum of Matrix A & B:");
for (int i = 0; i < SIZE; i++) {
System.out.print("[");
for (int j = 0; j < SIZE; j++) {
matrixC[i][j] = matrixA[i][j] + matrixB[i][j];
System.out.print(matrixC[i][j] + " ");
}
System.out.println("]");
}
}
/**
* Displays 5x5 Matrix.
*
* @param args
*/
public static void main(final String[] args) {
System.out.println("Matrix A:");
final int[][] matrixA = acceptMatrix();
System.out.println("Matrix B:");
final int[][] matrixB = acceptMatrix();
System.out.println("Sum of Matrices:");
addMatrix(matrixA, matrixB);
}
}