In: Computer Science
Java Linked Lists
I want a simple program that reads two text files that contains an integers matrix and store each file into a linked lists matrix
so I can later preform operations such as addition and subtraction on the matrices
an example of the input text files:
sample a
2 6 2
6 2 18
17 11 20
sample b
3 13 5
4 11 20
13 18 20

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
public class MatrixReader {
public static LinkedList<Integer> readMatrix(String fileName) {
try {
Scanner in = new Scanner(new File(fileName));
LinkedList<Integer> matrix = new LinkedList<>();
while(in.hasNextInt()) {
matrix.add(in.nextInt());
}
in.close();
return matrix;
} catch (FileNotFoundException e) {
return null;
}
}
public static LinkedList<Integer> addMatrices(LinkedList<Integer> l1,
LinkedList<Integer> l2) {
LinkedList<Integer> result = new LinkedList<>();
int size = l1.size();
if(l2.size() < size) {
size = l2.size();
}
for(int i=0; i<size; i++) {
result.add(l1.get(i) + l2.get(i));
}
return result;
}
public static void showMatrix(LinkedList<Integer> l) {
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
System.out.printf("%3d", l.get(i * 3 + j));
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
LinkedList<Integer> mat1 = readMatrix("mat1.txt");
LinkedList<Integer> mat2 = readMatrix("mat2.txt");
System.out.println("Matrix 1:");
showMatrix(mat1);
System.out.println("Matrix 2:");
showMatrix(mat2);
System.out.println("Addition: ");
showMatrix(addMatrices(mat1, mat2));
}
}
mat1.txt:
2 6 2
6 2 18
17 11 20
mat2.txt:
3 13 5
4 11 20
13 18 20
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.