2017-09-25 47 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(); 
      } 
     } 
    } 
} 

請注意評論 - 總體而言,您距功能代碼不遠,但錯誤非常重要。

相關問題