2011-10-17 72 views
1

读2D阵列说我有以下格式的文件:爪哇从文件

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

的文件的前两行表示一个二维数组的行数和列数。之后,每条线表示2D阵列的每一行的值。我正在尝试读取此文件并在java中创建一个2D整数数组。我尝试下面的代码:

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代码没有被正确读取该文件:

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(""); 
     } 
    } 
} 

,我看到的是输出。另外,我的代码抛出一个异常。我不确定是什么原因导致此异常。我似乎无法弄清楚我的代码有什么问题。谢谢!

回答

4

变化

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) { ..... 

阅读在每个循环

+0

谢谢!我不敢相信我忽略了这一点。 – sony

1

你(很明显)你的循环内没有readLine(),所以它只读取文件的第一行。

为什么还要指定行/列?为什么不从数据本身弄清楚呢?

+0

开始一个新行。如果我没有指定行/ columsn,我不知道矩阵的行数直到我读取文件的所有行。在那种情况下,我不确定如何在到达文件结尾之前初始化数组(矩阵=新的int [rows] [columns];)。我可能会错过某些东西。任何提示/谢谢! – sony

+0

我要么需要做文件的多个传递或使用额外的内部数据结构作为中介。这是一个优雅的方法,我不确定! – sony

+0

一个人通常不知道数据的大小。使用列表

1

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

你只是保持相同的永远在线和循环就可以了。