I've been having a problem writing a code that would read two files that contain matrices so for example,
FileA.txt
1 2 3
4 5 6
7 8 9
FileB.txt
0 1 2
3 4 5
6 7 8
then the program should read the files and the the two matrices and print the results as:
FileOut.txt
1 3 5
7 9 11
13 15 17
This is what I have thus far:
import java.util.Scanner; import java.io.File; // Matrix Addition public class Matrices { public final static String filename1 = "FileA.txt"; public final static String filename2 = "FileB.txt"; public static void main(String[] args) { Scanner inFile1; Scanner inFile2; String in1, in2; boolean eof = false, eol; int mv1, mv2, mvs; try { inFile1 = new Scanner(new File(filename1)); } catch (Exception e) { System.out.println("File could not be opened: " + filename1); System.exit(0); } try { inFile2 = new Scanner(new File(filename2)); } catch (Exception e) { System.out.println("File could not be opened: " + filename2); System.exit(0); } System.out.println("Result of the matrix addition\n"); //read file line by line until eof while (!eof) { if (((in1 = inFile1.readLine()) != null) && ((in2 = inFile2.readLine()) != null)) { //read and add all values per line eol = false; while (!eol) { if (((mv1 = in1.nextInt()) != null) && ((mv2 = in2.nextInt()) != null)) { mvs = mv1 + mv2; System.out.print(mvs + " "); } else eol = true; } // while (!eol) System.out.println(); } else eof = true; } // while (!eof) inFile1.close(); inFile2.close(); } }
I just need help completing the program. Thank you!