2016-03-04 116 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()

最后,有没有在你的代码示例讨论你想使用线程,或者为什么做什么。如果您有关于线程的问题,请将它们作为另一个问题打开,因为它们看起来与此无关。