-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathExercise08_05.java
101 lines (69 loc) · 2.62 KB
/
Exercise08_05.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package ch_08;
import java.util.Scanner;
/**
* 8.5 (Algebra: add two matrices)
* Write a method to add two matrices.
* The header of the method is as follows:
* <p>
* public static double[][] addMatrix(double[][] a, double[][] b)
* <p>
* In order to be added, the two matrices must have the same dimensions
* and the same or compatible types of elements. Let c be the resulting
* matrix. Each element cij is aij + bij. For example,
* for two 3 � 3 matrices a and b, c is
* <p>
* Write a test program that prompts the user to
* enter two 3 � 3 matrices and displays their sum.
*/
public class Exercise08_05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter matrix one now: ");
double[][] matrix1 = new double[3][3];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
matrix1[i][j] = input.nextDouble();
}
}
System.out.println("Enter matrix two now: ");
double[][] matrix2 = new double[3][3];
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[i].length; j++) {
matrix2[i][j] = input.nextDouble();
}
}
double[][] newMatrix = addMatrix(matrix1, matrix2);
System.out.println("The addition of the matrices is: ");
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
System.out.print(matrix1[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" + ");
} else if (i != 1 && j == 2)
System.out.print(" ");
}
for (int j = 0; j < matrix2[i].length; j++) {
System.out.print(matrix2[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" = ");
} else if (i != 1 && j == 2)
System.out.print(" ");
}
for (int j = 0; j < newMatrix[i].length; j++) {
System.out.print(newMatrix[i][j] + " ");
if (i != 1 && j == 2)
System.out.print(" ");
}
System.out.println();
}
}
public static double[][] addMatrix(double[][] a, double[][] b) {
double[][] sum = new double[3][3];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
return sum;
}
}