2016-03-04 118 views
-1

所以我有一個我需要使用10個線程從矩陣.txt文件中讀取數據的10列的分配。我無法將文件轉換爲2d數組,因爲我總是得到一個NumberFormatException異常。文件的樣式爲10列和1000行10k元素。在txt文件中,數字格式化爲每個記錄之間具有不同空格的列。Java的閱讀txt文件,以2維數組

 
9510.0  5880.0  8923.0  21849.0  3295.0  17662.0  23931.0  31401.0  13211.0  18942.0  
11034.0  9002.0  4162.0  4821.0  4217.0  7849.0  22837.0  19178.0  24492.0  14838.0  
7895.0  7337.0  18115.0  8949.0  28492.0  22067.0  12714.0  21234.0  26497.0  18003.0  
846.0  29493.0  21868.0  26037.0  27137.0  28630.0  20373.0  8274.0  21280.0  11475.0  
26069.0  21295.0  16883.0  4448.0  20317.0  21063.0  3540.0  23934.0  14843.0  2757.0  
19348.0  32207.0  7833.0  5495.0  26138.0  20905.0  16135.0  19840.0  10829.0  5993.0  
12538.0  16205.0  18997.0  29450.0  6740.0  970.0  7004.0  17142.0  677.0  23509.0  
5243.0  14107.0  24050.0  8179.0  20050.0  24130.0  13494.0  22593.0  3032.0  7580.0  

這裏是我一直在測試的代碼以及掃描儀的實現。

import java.io.*; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.*; 

import javax.swing.JOptionPane; 

import java.io.*; 
import java.util.*; 

public class MainThread { 

    public static int rows, cols; 
    public static int[][] cells; 
    /** 
    * main reads the file and starts 
    * the graphical display 
    */ 
    public static void main(String[] args) throws Exception { 

     // Read the entire file in 
     List<String> myFileLines = Files.readAllLines(Paths.get("bigMatrix.txt")); 

     // Remove any blank lines 
     for (int i = myFileLines.size() - 1; i >= 0; i--) { 
      if (myFileLines.get(i).isEmpty()) { 
       myFileLines.remove(i); 
      } 
     } 

     // Declare you 2d array with the amount of lines that were read from the file 
     double[][] intArray = new double[myFileLines.size()][]; 

     // Iterate through each row to determine the number of columns 
     for (int i = 0; i < myFileLines.size(); i++) { 
      // Split the line by spaces 
      String[] splitLine = myFileLines.get(i).split("\\s"); 

      // Declare the number of columns in the row from the split 
      intArray[i] = new double[splitLine.length]; 
      for (int j = 0; j < splitLine.length; j++) { 
       // Convert each String element to an integer 
       intArray[i][j] = Integer.parseInt(splitLine[j]); 
      } 
     } 

     // Print the integer array 
     for (double[] row : intArray) { 
      for (double col : row) { 
       System.out.printf("%5d ", col); 
      } 
      System.out.println(); 
     } 
    } 


    } 

任何幫助將是巨大的,我也知道了一些關於線程,實現Runnable接口,但如何與平均thatd一起計算每列的最大值任何想法是真棒。

回答

0

由於異常的名稱暗示,9510.0例如不是正確的整數格式,因爲.0部分意味着一個浮點數或一個double。使用Float.parseFloat()float數組或者如果你真的想要,鑄造與intArray[i][j] = (int) Float.parseFloat(splitLine[j]);

0

詮釋有(至少)兩個問題與您的代碼,可導致NumberFormatException異常。

第一個是,你正在做split("\\s")將各執一個空白字符。這意味着彼此相鄰的兩個空格將導致空字符串「在」它們之間,並且此空字符串不能解析爲數字。

第二個是,你在那些非整數(他們有一個小數部分)使用數字Integer.parseInt()。您可能需要Double.parseDouble()

最後,有沒有在你的代碼示例討論你想使用線程,或者爲什麼做什麼。如果您有關於線程的問題,請將它們作爲另一個問題打開,因爲它們看起來與此無關。