Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying matrixes from two different txt files

Tags:

java

matrix

I am currently trying to multiply two different matrix that are in two different files in java. The goal is to take the matrixes that are in two different txt files and multiply them together. Once the multiplication is done (if it is possible) then it should print the answer out into a different txt file. However, I am keep getting this error:

Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.base/java.util.Scanner.nextLine(Scanner.java:1651)  
  at MM.readMatrixFromFile(MM.java:38)  
  at MM.main(MM.java:15)  

I've double check to see if the txt files were in the correct place (which they are) and I have checked to see were there anything in my code that I have missed, but I have found nothing. Can someone please help me know what I am doing wrong (code shown below):

/*
* Here we are creating the matrix program, where we will multiply two matrixes from the two given matrix files. 
* Once we make the conversion, we will print out the result in another txt file
* In order to do this project, we may need to 
*/

import java.io.*;
import java.util.*;

public class MM {

    public static void main(String[] args) {
        int[][] matrixA = readMatrixFromFile("matrixA.txt");
        int[][] matrixB = readMatrixFromFile("matrixB.txt");

        if (matrixA[0].length != matrixB.length) {
            System.out.println("Unable to perform matrix multiplication.");
            return;
        }

        int[][] matrixC = multiplyMatrices(matrixA, matrixB);
        writeMatrixToFile(matrixC, "matrixAnswer.txt");
    }

    private static int[][] readMatrixFromFile(String filename) {
        try {
            File file = new File(filename);
            Scanner scanner = new Scanner(file);

            int numRows = getNumRows(file);
            int numCols = getNumCols(scanner.nextLine());

            int[][] matrix = new int[numRows][numCols];

            for (int i = 0; i < numRows; i++) {
                String[] values = scanner.nextLine().split(" ");
                for (int j = 0; j < numCols; j++) {
                    matrix[i][j] = Integer.parseInt(values[j]);
                }
            }

            scanner.close();
            return matrix;

        } catch (IOException e) {
            System.out.println("Error reading matrix from file: " + filename);
            return null;
        }
    }

    private static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB) {
        int numRowsA = matrixA.length;
        int numColsA = matrixA[0].length;
        int numColsB = matrixB[0].length;

        int[][] matrixC = new int[numRowsA][numColsB];

        for (int i = 0; i < numRowsA; i++) {
            for (int j = 0; j < numColsB; j++) {
                for (int k = 0; k < numColsA; k++) {
                    matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }

        return matrixC;
    }

    private static void writeMatrixToFile(int[][] matrix, String filename) {
        try {
            File file = new File(filename);
            FileWriter writer = new FileWriter(file);

            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[0].length; j++) {
                    writer.write(matrix[i][j] + " ");
                }
                writer.write("\n");
            }

            writer.close();

        } catch (IOException e) {
            System.out.println("Error writing matrix to file: " + filename);
        }
    }

    private static int getNumRows(File file) throws IOException {
        Scanner scanner = new Scanner(file);
        int numRows = 0;
        while (scanner.hasNextLine()) {
            scanner.nextLine();
            numRows++;
        }
        scanner.close();
        return numRows;
    }

    private static int getNumCols(String line) {
        return line.trim().split(" +").length;
    }
}

and here is how I have it set up in my file: File setup

like image 411
Rayman Avatar asked Dec 05 '25 15:12

Rayman


1 Answers

You are not checking if the scanner actually has lines to read. I see you iterate from 0 to numRows and you use lower than (<).

However, you are calling nextLine() to get your numCols, and that is consuming one line (thus I suspect that you are attempting to read one line extra than the ones you actually have):

int numRows = getNumRows(file);
int numCols = getNumCols(scanner.nextLine()); //here you are consuming one line
int[][] matrix = new int[numRows][numCols];

for (int i = 0; i < numRows; i++) { //...but you still iterate till numRows
    //I suspect that a numRows-1 will solve this
    String[] values = scanner.nextLine().split(" ");
    //...
}

I suspect that you should have numRows -1 instead. Or better yet, call hasNextLine() to be sure you still have lines to read. Otherwise you will be "missing" that first line you read to get the number of columns.

if(scanner.hasNextLine()){
    proceedToRead();
}
like image 92
DarkCygnus Avatar answered Dec 08 '25 04:12

DarkCygnus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!