簡體   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