1

I am trying to read a .txt file with a certain format and fill it into a matrix in Java.

The text file has following format:

123
456

I have the following code, that creates the matrix based on the .txt file with the right dimension(2 rows, 3 columns in this case).

public static int [][] readMatrix(String url)
            throws FileNotFoundException {


        int m = 1;
        String URL = '.\src\User\url.txt'; 

        File file = new File((url));
        Scanner sc = new Scanner(file);

        String line = sc.nextLine();
        int n = line.length();

        while (sc.hasNextLine()) {
            m+= 1;
            sc.nextLine();
        }
    int [][] matrix = new int[m][n];

    return matrix;
    }

In the next step, I want to fill out the matrix with the content from the .txt file, I tried using a Scanner but I couldn't figure out the syntax to iterate properly.

Any suggestions?

Thanks in advance!

3 Answers3

1

One of the ways you can achieve this by following the steps:

  • Iterate over file (one line at a time)
  • Read line and split it into array
  • Iterate over the number of columns and populate the columns for the row

Here is a sample program/excerpt that you can refer to (replace the hard coded values for rows and cols variables - you've already calculated these):

try {
        int rows = 2;
        int cols = 3;
        int [][] matrix = new int[rows][cols];

        Scanner scanner = new Scanner(file);

        int rowIdx = 0;
        
        // Iterate over each line
        while(scanner.hasNextLine()){
            // Read a line
            String line = scanner.nextLine();

            // Split into array
            char[] arr = line.toCharArray();
            
            // Populate matrix
            for(int colIdx=0; colIdx< cols; colIdx++){
                matrix[rowIdx][colIdx] = 
                Character.getNumericValue(arr[colIdx]);
            }
            
            // Increment current 'row' index 
            rowIdx++;
        }
        
        // This is just to print the array(matrix) and confirm that it is populated correctly
        for(int i =0; i<matrix.length; i++){
            System.out.println(Arrays.toString(matrix[i]));
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

NOTE: This program uses Character.getNumericValue - be careful using this as it may not always work as you may expect (specially for non numeric values). Make sure to read the documentation here

Vini
  • 8,299
  • 11
  • 37
  • 49
0

Since you already know how to read the file to get the number of lines in each row or column, all you need to do is read through it again, or store it the first time around in ArrayList<String> array.

Lets say you stored each parsed line in a String array. You could iterate back through each string and parse through the characters to get your values.

ArrayList<String> array = new ArrayList<String>();
// Iterate through each line and add the strings to the array...
// Then create your matrix of the dimensions you just gathered.
int[][] matrix = new int[m][n];
for (int i=0; i<matrix.length; i++) {
    String[] split = array.get(i).split(""); // Stores each value from the string, split to an array by each character
    for (int j=0; j<split.length; j++) { // Loops through each value in the string array
        matrix[i][j] = Integer.parseInt(split[j]); // Adds the value to the matrix
    }
}

Now, if you end up with a file with values separated by spaces or something, all you'd need to do to make it match is change the regex in the .split("") line.

Assuming you didn't store the Strings into an array, however, you could loop through your file once more, and do the same process, splitting the sc.nextLine() into a String[] array.

Hope this helps.

0

It's hardly worth working over a text file for two small integer numbers so we should assume that the text file could also potentially hold something like:

342354645686786
423423689909754
677554345952536
238884546869621
345665678683481
342354645686786
423423689909754
677554345952536
238884546869621
345665678683481
342354645686786
423423689909754
677554345952536
238884546869621
423423689909754

Perhaps we may never know exactly what is in the file other than it contains several lines of digits. With this mind, don't try to initially fill an int[][] Array with the digits in file since we may never know what to initialize the 2D Array with, instead use an ArrayList or List Interface to store an int[] array for each line as they are read in because they can grow dynamically where as an Array can not. Each int[] array contained within the List can then be placed into the matrix (2D) Array once all the data is collected, for example:

public static int[][] readMatrix(String url) throws FileNotFoundException {
    File file = new File((url));
    
    java.util.List<int[]> listOfArrays = new java.util.ArrayList<>(); 
    String line;
    
    // 'Try With Resources' used here to auto-close the reader and free resources.
    try (Scanner sc = new Scanner(file)) {
        while (sc.hasNextLine()) {
            line = sc.nextLine().trim();
            
            /* Line Validation:
               Skip blank lines (if any) or any line that does 
               not contain all digits.               */
            if (line.isEmpty() || !line.matches("\\d+")) { 
                continue; 
            } 
            
            /* Declare and initialize an int[] Array to the 
               number of dogot in line.                */
            int[] array = new int[line.length()];
            for (int i = 0; i < line.length(); i++) {
                array[i] = Integer.parseInt(String.valueOf(line.charAt(i)));
            }
            
            // Add the newly created array into the List.
            listOfArrays.add(array);
        }
    }
    
    /* Now that the file is all read in, we can create 
       the matrix. Don't supply an initialization value 
       for the inner arrays because for all we know this 
       might end up being a stagarded matrix. It doesn't 
       need a value.         */
    int[][] matrix = new int[listOfArrays.size()][];
    
    /* Iterate through the list and apply the int[]
       arrays in the list to the matrix[][]. Remember,
       a 2D Array is an Array of Arrays in Java.   */
    for (int i = 0; i < listOfArrays.size(); i++) {
        matrix[i] = listOfArrays.get(i);
    }
    return matrix; // Return the created matrix.
}

To run this method against the file data shown above you might do something like this:

int[][] matrix = null;
try {
    matrix = readMatrix(url);
}
catch (Exception ex) {
    System.err.println(ex.getMessage());
}
    
if (matrix != null) {
    for (int[] ary : matrix) {
        System.out.println(Arrays.toString(ary).replaceAll("[\\[\\],]", ""));
    }
}

And the Console Window would display:

3 4 2 3 5 4 6 4 5 6 8 6 7 8 6
4 2 3 4 2 3 6 8 9 9 0 9 7 5 4
6 7 7 5 5 4 3 4 5 9 5 2 5 3 6
2 3 8 8 8 4 5 4 6 8 6 9 6 2 1
3 4 5 6 6 5 6 7 8 6 8 3 4 8 1
3 4 2 3 5 4 6 4 5 6 8 6 7 8 6
4 2 3 4 2 3 6 8 9 9 0 9 7 5 4
6 7 7 5 5 4 3 4 5 9 5 2 5 3 6
2 3 8 8 8 4 5 4 6 8 6 9 6 2 1
3 4 5 6 6 5 6 7 8 6 8 3 4 8 1
3 4 2 3 5 4 6 4 5 6 8 6 7 8 6
4 2 3 4 2 3 6 8 9 9 0 9 7 5 4
6 7 7 5 5 4 3 4 5 9 5 2 5 3 6
2 3 8 8 8 4 5 4 6 8 6 9 6 2 1
3 4 5 6 6 5 6 7 8 6 8 3 4 8 1
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22