Skip to content

Reading and print 2D matrix (array) to console from created File | Java

Necessary create a 2D matrix (array) sizes m*b:

  1. Filled in by manually, found Null, print results
  2. Filled in by automatically:
  • create a File -> record File.txt
  • read in created File.txt
  • found Null
  • print results
    package labs1;
    
    import java.io.*;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.*;
    
    public class labs2 {
        public static void main(String[] args) throws Exception {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
            System.out.println("Add size matrix m*n nnumber of row m =");
            int m = Integer.parseInt(reader.readLine());
    
            System.out.println("number of columns n =");
            int n = Integer.parseInt(reader.readLine());
    
            int[][] matrix = new int[m][n];
    
            System.out.println("Choose to method assignments matrix n0-manually n1-automatically");
            int k = Integer.parseInt(reader.readLine());
    
            while (true) {
                if (k == 0) {
    
                    //
                    for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                            matrix[i][j] = Integer.parseInt(reader.readLine());
                        }
                    }
                    // print matrix
                    for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                            System.out.print(matrix[i][j] + " ");
                        }
                        System.out.println("");
                    }
    
                    //count of null in matrix
                    int count = 0;
    
                    for (int i = 0; i < matrix.length; i++) {
                        for (int j = 0; j < matrix[i].length; j++)
                            if (matrix[i][j] == 0) {
                                count++;
                            }
                    }
                    System.out.println("Quantity of Null in matrix: " + count);
    
                }
                //Assignment matrix automatically - Random
                if (k == 1) {
                    for (int i = 0; i < matrix.length; i++) {
                        // do the for in the row according to the column size
                        for (int j = 0; j < matrix[i].length; j++) {
                            // multiple the random by 10 and then cast to in
                            matrix[i][j] = ((int) (Math.random() * 10));
                        }
                    }
    
                    // print matrix
                    for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                            System.out.print(matrix[i][j] + " ");
                        }
                        System.out.println("");
                    }
    
                    //count of null in matrix
                    int count = 0;
    
                    for (int i = 0; i < matrix.length; i++) {
                        for (int j = 0; j < matrix[i].length; j++)
                            if (matrix[i][j] == 0) {
                                count++;
                            }
                    }
                    System.out.println("Quantity of Null in matrix: " + count);
    
    
                    //Create a File .txt
    
                    // String Builder to create the table structure before writing it to the file.
                    StringBuilder sb = new StringBuilder();
    
                    for (int[] int1 : matrix) {
                        for (int j = 0; j < int1.length; j++) {
                            sb.append(int1[j]).append("t");                    // Add tab to delimite the elements
                        }
                        sb.append("n");                                      // Add new line character
                    }
    
                    System.out.println("nMatrix record in filen" + sb);
    
                    // The path to your file
                    Path path = Paths.get("D:\labs1.txt");
    
                    // Writes to that path the bytes in the string from the stringBuilder object.
                    Files.write(path, sb.toString().getBytes());
    
    
                    ArrayList<int[]> list = readMaze("D:\labs1.txt");
    
    
                    System.out.println(Arrays.toString(list.toArray()));
                }
                if (k != 0 | k != 1) {
                    break;
                }
            }
        }
    
        //Reading in File
    
        public static ArrayList<int[]> readMaze(String fileName) {
    
            // Number of ints per line:
            int width = 2;
    
            // This will be the output - a list of rows, each with 'width' entries:
            ArrayList<int[]> results = new ArrayList<int[]>();
    
            String line = null;
    
            try {
                FileReader fileReader = new FileReader(fileName);
    
                BufferedReader bufferedReader = new BufferedReader(fileReader);
    
                Scanner mazeRunner = new Scanner(bufferedReader);
    
                // While we've got another line..
                while (mazeRunner.hasNextLine()) {
    
                    // Setup current row:
                    int[] row = new int[width];
    
                    // For each number..
                    for (int i = 0; i < width; i++) {
    
                        // Read the number and add it to the current row:
                        row[i] = mazeRunner.nextInt();
    
                    }
    
                    // Add the row to the results:
                    results.add(row);
    
                    // Go to the next line (optional, but helps deal with erroneous input files):
                    if (mazeRunner.hasNextLine()) {
    
                        // Go to the next line:
                        mazeRunner.nextLine();
    
                    }
    
                }
    
                mazeRunner.close();
    
            } catch (FileNotFoundException ex) {
                System.out.println("Unable to open file: " + fileName);
            } catch (IOException ex) {
                System.out.println("Error reading file: " + fileName);
            }
    
            return results;
        }
    }

I used public static readMaze from here – https://stackoverflow.com/questions/41632526/reading-a-text-file-into-a-2d-array

Print to the console:

Add size matrix m*n 
number of row m =
4
number of columns n =
2
Choose to method assignments matrix 
0-manually 
1-automatically
1
1 0 
9 3 
6 3 
0 2 
Quantity of Null in matrix: 2

Matrix record in file
1   0   
9   3   
6   3   
0   2   

[[[email protected], [[email protected], [[email protected], [[email protected]]

Process finished with exit code 0

But this code incorrect reading and printing 2D matrix(array) [[[email protected], [[email protected], [[email protected], [[email protected]]

I doubt about this code:

ArrayList<int[]> list = readMaze("D:\labs1.txt"); System.out.println(Arrays.toString(list.toArray()));

Please Help me, this’s need me to finish task in the University

Answer

You are getting this result because you are printing the elements of ArrayList instead of the int[] arrays contained within that ArrayList. It should be something like this:

Replace this code (only):

ArrayList<int[]> list = readMaze("D:\labs1.txt");

System.out.println(Arrays.toString(list.toArray()));

With this code:

ArrayList<int[]> list = readMaze("D:\labs1.txt");
for (int[] intArray : list) {
    System.out.println(Arrays.toString(intArray));
}