2017-09-25 49 views
0

免责声明:这是作业,所以我不想找到确切的答案,因为我想自己做这件事。 我必须从充满双打的文本文件中读取一个矩阵,并将其放入二维数组中。 我目前正在努力寻找我的问题在我的代码中的确切位置,因为我知道如何使用内置的Java扫描器来创建正常的数组。我的代码总是给我一个NullPointerException错误,这意味着我的矩阵二维数组是空的。读一个充满双打的文本文件到一个二维数组中

public Matrix(String fileName){ 
    //reads first double and puts it into the [1][1] category 
    //then moves on to the [1][2] and so on 
    //once it gets to the end, it switches to [2][1] 
    Scanner input = new Scanner(fileName); 
    int rows = 0; 
    int columns = 0; 
    while(input.hasNextLine()){ 
     ++rows; 
     Scanner colReader = new Scanner(input.nextLine()); 
     while(colReader.hasNextDouble()){ 
      ++columns; 
     } 
    } 
    double[][]matrix = new double[rows][columns]; 
    input.close(); 

    input = new Scanner(fileName); 
    for(int i = 0; i < rows; ++i){ 
     for(int j = 0; j < columns; ++j){ 
      if(input.hasNextDouble()){ 
       matrix[i][j] = input.nextDouble(); 
      } 
     } 
    } 
} 

我的文本文件:

1.25 0.5 0.5 1.25 
0.5 1.25 0.5 1.5 
1.25 1.5 0.25 1.25 
+0

NullPointerException发生在哪里?查看堆栈跟踪并查看是否可以确定发生异常的行。 – Defenestrator

+1

@Ravi这个问题非常笼统,过于宽泛。我不打算把这个问题作为这个问题的重复来解决。 – Defenestrator

+0

@Defenestrator错误发生在我的* toString()*函数中,这是我的嵌套for循环的第一个看到2d数组的长度。 – Michael

回答

1

代码有几个错误的 - 而且由于它的功课,我会尽力坚持你最初的设计尽可能:

public Matrix(String fileName){ 

    //First issue - you are opening a scanner to a file, and not its name. 
    Scanner input = new Scanner(new File(fileName)); 
    int rows = 0; 
    int columns = 0; 

    while(input.hasNextLine()){ 
     ++rows; 
     columns = 0; //Otherwise the columns will be a product of rows*columns 
     Scanner colReader = new Scanner(input.nextLine()); 
     while(colReader.hasNextDouble()){ 
      //You must "read" the doubles to move on in the scanner. 
      colReader.nextDouble(); 
      ++columns; 
     } 
     //Close the resource you opened! 
     colReader.close(); 
    } 
    double[][]matrix = new double[rows][columns]; 
    input.close(); 

    //Again, scanner of a file, not the filename. If you prefer, it's 
    //even better to declare the file once in the beginning. 
    input = new Scanner(new File(fileName)); 
    for(int i = 0; i < rows; ++i){ 
     for(int j = 0; j < columns; ++j){ 
      if(input.hasNextDouble()){ 
       matrix[i][j] = input.nextDouble(); 
      } 
     } 
    } 
} 

请注意评论 - 总体而言,您距功能代码不远,但错误非常重要。

相关问题