从文件读取数据到二维数组

时间:2019-05-18 02:40:41

标签: java multidimensional-array java.util.scanner

我需要读取以下格式的带有魔方的文件:      #

 # # #
 # # #
 # # #

其中第一行表示正方形大小,并使用文件值创建2d数组。

我设置了readMatrix方法以读取行,创建了正确大小的2d数组,并将每个值输入到其正确位置。

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;

但是,此程序的测试仪显示了正确尺寸的幻方,但所有值均为0,并且使getMatrix方法失败(我假设是因为返回的平方与文件平方不匹配)。我尝试在readMatrix中的for / while循环中(内部/外部)循环移动扫描仪对象,并尝试使用parseInt / scan next而不是nextInt进行成功。我很沮丧。

1 个答案:

答案 0 :(得分:0)

尝试此代码能够显示3 x 3矩阵中的1-9。变量类型可以根据需要进行更改。我使用'char'是为了方便。

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;
}