繁体   English   中英

Java从文件读取二维数组

[英]Java Reading a 2D array from a file

说我有以下格式的文件:

3
4
1,2,3,4
5,6,7,8
9,10,11,12

文件的前两行代表2D数组的行数和列数。 此后,每一行代表2D阵列每一行的值。 我正在尝试读取此文件并在Java中创建2D整数数组。 我尝试了以下代码:

public class PrintSpiral {
    private static BufferedReader in = null;
    private static int rows = 0;
    private static int columns = 0;
    private static int [][] matrix = null;
    public static void main(String []args) throws Exception {
        try {
            String filepath = args[0];
            int lineNum = 0;

            int row=0;
            in = new BufferedReader(new FileReader(filepath));
            String line = in.readLine();
            while(line!=null) {
                lineNum++;
                if(lineNum==1) {
                    rows = Integer.parseInt(line);
                    System.out.println("The number of rows of the matrix are: " + rows);
                } else if(lineNum==2) {
                    columns = Integer.parseInt(line);
                    System.out.println("The number of columns of the matrix are: " + columns);
                    matrix = new int[rows][columns];
                } else {
                    String [] tokens = line.split(",");
                    for (int j=0; j<tokens.length; j++) {
                        System.out.println("I am filling the row: " + row);
                        matrix[row][j] = Integer.parseInt(tokens[j]);
                    }
                    row++;
                }
            }
        } catch (Exception ex) {
            System.out.println("The code throws an exception");
            System.out.println(ex.getMessage());
        } finally {
            if (in!=null) in.close();
        }
        System.out.println("I am printing the matrix: ");
        for (int i=0; i < rows; i++) {
            for(int j=0; j < columns; j++)
                System.out.print(matrix[i][j]);
            System.out.println("");
        }
    }
}

我看到的输出是:

The number of rows of the matrix are: 3
The number of columns of the matrix are: 3
I am filling the row: 0
I am filling the row: 1
I am filling the row: 2
I am filling the row: 3
The code throws an exception
3
I am printing the matrix: 
300
300
300
3 0 0 0 0 0 3 3 0

显然,Java代码无法正确读取文件。 另外,我的代码抛出异常。 我不确定是什么原因导致此异常。 我似乎无法弄清楚我的代码出了什么问题。 谢谢!

更改

in = new BufferedReader(new FileReader(filepath));
String line = in.readLine();
while(line!=null) { .....

in = new BufferedReader(new FileReader(filepath));
String line = null;
while((line = in.readLine()) !=null) { .....

在每个循环的开始读取新行

您(很显然)在循环内没有readLine(),因此它只读取文件的第一行。

为什么要麻烦指定行/列? 为什么不仅仅从数据本身中找出原因呢?

在while循环的末尾,添加in.readline();

您只是永远保持同一行并循环播放。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM