2017-09-09 20 views
-3

我被困在一個非常簡單的練習中,並且在代碼中找不到錯誤。使用掃描儀將浮點數從.txt讀取到浮點矩陣

我有一個文本文件,它看起來像這樣:

230.24415 134.34523 166.47234

192.02849 138.28403 294.12875

198.97356 256.49284 140.41526

第一(int eger)數字表示矩陣尺寸,在這種情況下是3x3,以下值是由空格和換行符分隔的5位小數位數的浮點數,必須將它們設置在矩陣中以便與它們一起操作。這是這個練習的主要問題。

下面是代碼:

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class fileToMatrix { 

    public static void main(String[] args) throws IOException { 

     File f = new File("./src/floatMat.txt"); 
     Scanner s = null; 

     int m=-1; 
     float value = -0.1f; 

     try { 

      s = new Scanner(f); 

      if(s.hasNextLine()) { // Firstly, read the dimension number 
       m = s.nextInt(); 
       System.out.println("Dimension of the matrix = " + m + "x" + m); 

      } 

      float [][] mat = new float[m][m]; //creates a matrix of dimension m 
      for(int i=0; i< m; i++){ //and initializes to 0 
       for(int j=0; j< m; j++){ 
        mat[i][j] = 0.0f; 
       }    
      } 

      if(s.hasNextLine()) { 
       for(int r=0; r< m; r++){ 
        for(int c=0; c< m; c++){ 
         value = s.nextFloat(); //PROBABLY HERE'S THE MISTAKE!!!!! 
         mat[r][c] = value; //set value on the current cell of the array 
        }    
       } 
      } 

      for(int i=0; i< m; i++){ //print the matrix 
       for(int j=0; j< m; j++){ 
        System.out.print(mat[i][j]+ " "); 
       } 
       System.out.println(); 
      } 


     } catch (Exception ex) { 
      System.out.println("Message catch: " + ex.getMessage()); 
     } finally { 
      if (s != null) 
        s.close(); 
     } 
    } 
    } 

我敢肯定,這個錯誤是在我的意見通知的錯誤,因爲它似乎不承認我的.TXT的浮點數。實際上,如果我在我的.txt文件中輸入整數,它幾乎可以工作!

它只打印「矩陣的維數= 3x3」,但打印出「消息catch:null」,它甚至不打印填充的矩陣。

謝謝大家,感謝您的幫助!

+0

替換'的System.out.println( 「消息捕獲:」 + ex.getMessage());''與ex.printStackTrace();'檢查例外是什麼以及線拋出它。 – Oleg

回答

1
if(s.hasNextLine()) { 
    for(int r=0; r< m; r++){ 
     for(int c=0; c< m; c++){ 
      value = s.nextFloat(); //PROBABLY HERE'S THE MISTAKE!!!!! 
      mat[r][c] = value; //set value on the current cell of the array 
     }    

此時,您已經閱讀所有三個(ñ)花車就行了,所以你需要s.nextLine()這裏前進到下一行。

} 
} 
+0

的確,我需要對下一條線進行研究。在if(s.hasNextLine())之前也需要放入's.nextLine()'。但它仍然無法正常工作,主要問題是該程序不讀任何浮點數......無論如何謝謝你,@EJP – 0xGolovkin

+0

適合我。你一定是做錯了。 – EJP