Reading data from file into 2d array

52
May 18, 2019, at 9:50 PM

I need to read a file with a magic square in the format of: #

 # # #
 # # #
 # # #

where the first line represents the square size and create a 2d array with the file values.

I set up my readMatrix method to read through the lines, created a 2d array of the correct size and input each value to its correct position.

private int[][] readMatrix(String fileName) throws    
FileNotFoundException {
    int n;
    File file = new File(fileName);
    Scanner fileScan = new Scanner(file);
    String line = fileScan.nextLine();
    Scanner lineScan = new Scanner(line);
    n = lineScan.nextInt();
    square = new int[n][n];
    while (fileScan.hasNextLine()) {
        line = fileScan.nextLine();
        while (lineScan.hasNext()) {
            for (int i = 0; i < n; i++) {
                lineScan = new Scanner(line);
                for (int j = 0; j < n; j++) {
                    square[i][j] = lineScan.nextInt();
                }
            }
        }
    }
    fileScan.close();
    lineScan.close();
    return square;
public int[][] getMatrix() {
    int[][] copy;
    int n = square.length;
    copy = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            copy[i][j] = square[i][j];
        }
    }
    return copy;

However the tester for this program displays a magic square of the correct dimensions but with all the values being 0 and fails the getMatrix method(I'm assuming because the returned square doesn't match the file square). I tried moving the scanner objects around(inside/outside) the for/while loops in the readMatrix and tried using parseInt/scan next instead of nextInt with no success. I am stumped.

Answer 1

Try this code is able to display 1 - 9 from the 3 x 3 matrix. The variable type can be changed to your need. I used 'char' for ease.

private static char[][] finalmatrix;
public static void main(String[] args) throws Exception {
    finalmatrix = readMatrix("File.txt");
    // Output matrix.
    for (int i = 0; i < finalmatrix.length ;i++) {
        for (int j = 0; j < finalmatrix[i].length ;j++) {
            System.out.print(finalmatrix[i][j] + " ");
        }
        System.out.println("");
    }
}
private static char[][] readMatrix(String fileName) throws IOException {
    File file = new File(fileName);
    Scanner scan = new Scanner(file);
    int countRow = 0;
    int countColumn = 0;
    List temp = new ArrayList();
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        for (int i = 0; i < line.length(); i++) {
            // Count the number of columns for the first line ONLY.
            if (countRow < 1 && line.charAt(i) != ' ') {
                countColumn++;
            }
            // Add to temporary list.
            if (line.charAt(i) != ' ') {
                temp.add(line.charAt(i));
            }
        }
        // Count rows.
        countRow++;
    }
    char[][] matrix = new char[countRow][countColumn];
    // Add the items in temporary list to matrix.
    int count = 0;
    for (int i = 0; i < matrix.length ;i++) {
        for (int j = 0; j < matrix[i].length ;j++) {
            matrix[i][j] = (char) temp.get(count);
            count++;
        }
    }
    scan.close();
    return matrix;
}
READ ALSO
Direct self-reference leading to cycle error when I convert CompletionStage&lt;PagedList&lt;Home&gt;&gt; to json using following code?

Direct self-reference leading to cycle error when I convert CompletionStage<PagedList<Home>> to json using following code?

Using java-paly-ebean-exmaple 27, I am converting html view response to json rest response for list action, and I am getting following error:

71
Elastic Search Filter Bucket Values

Elastic Search Filter Bucket Values

My use case is as follows, I need to find out all the unique colors that had appeared in last 1 year but went disappearing in last 3 monthsSo my documents looks like this

77
Reading from a file using scanner, line by line and creating an object out of the data

Reading from a file using scanner, line by line and creating an object out of the data

I am tasked with reading a file line by line using scanner and creating Student objects from each line

68