Question:
How to find the sum of to matrices from two different files?
Answer:
In this example we populate one 4x4 matrix from the sum of two different 4x4 matrices files.
Code:
import java.io.*; import java.util.*; public class Matrices { public static void main(String[] args) { File f1 = new File("m1.txt"); File f2 = new File("m2.txt"); int[][] m1 = new int[4][4]; int[][] m2 = new int[4][4]; int[][] m3 = new int[4][4]; try { Scanner sc1 = new Scanner(f1); Scanner sc2 = new Scanner(f2); for (int i=0; i<4; i++) { for (int j=0; j<4; j++) { m1[i][j]=sc1.nextInt(); m2[i][j]=sc2.nextInt(); m3[i][j]=m1[i][j]+m2[i][j]; } } } catch (Exception e) { } System.out.println("m1: " + Arrays.deepToString(m1)); System.out.println("m2: " + Arrays.deepToString(m2)); System.out.println("m3: " + Arrays.deepToString(m3)); } }
Output:
$ cat m1.txt 1 3 5 -1 4 8 -7 9 1 -1 3 8 9 11 6 8 $ cat m2.txt 6 11 3 7 9 -5 -8 -3 1 15 6 8 -2 -1 5 0 $ java Matrices m1: [[1, 3, 5, -1], [4, 8, -7, 9], [1, -1, 3, 8], [9, 11, 6, 8]] m2: [[6, 11, 3, 7], [9, -5, -8, -3], [1, 15, 6, 8], [-2, -1, 5, 0]] m3: [[7, 14, 8, 6], [13, 3, -15, 6], [2, 14, 9, 16], [7, 10, 11, 8]]