【问题标题】:JAVA: how do I convert a txt file into a 2-D array with numbers in E notation?JAVA:如何将 txt 文件转换为带有 E 表示法数字的二维数组?
【发布时间】:2016-12-03 23:07:08
【问题描述】:

我有一个 .txt 文件,其中包含 300 行和 785 列,其中包含一堆 E 表示法的数字(例如 -6.431571950262252035e-02)。我如何将这些数字转换为二维数组?

这就是我所拥有的:

 double[][] hiddenArray = new double[300][785];  

 Scanner scanner = new Scanner(System.in) ;
 String hiddenFile = "hidden-weights.txt";
 String outputFile = "output-weights.txt";
 scanner.close();

 Scanner in = new Scanner(new File(hiddenFile));
 String hidden= in.nextLine();

【问题讨论】:

    标签: java multidimensional-array scientific-notation


    【解决方案1】:

    使用Scanner::hasNext() 在有更多行时循环,Scanner::nextLine() 获取下一行,然后使用String::split() 获取每行上的字符串数组(注意:我的假设是列由逗号(即,),但请随时根据您的需要进行调整)。要解析 e 表示法中的数字,请使用 Double.valueof(),并将该值添加到数组中(例如 hiddenArray)。

    您应该可以使用下面的示例。我还在tutorialspoint.com codingGround 上创建了一个示例,但这可能不起作用...

        try {
            String delimiter = ","; //separates columns - change for your needs
    
            int row = 0;
            Scanner in = new Scanner(new File(hiddenFile));
            String line;
            while (in.hasNext() && (line = in.nextLine()) != null )   {
                String[] vals = line.trim().split(",");
    
                for (int col = 0; col < vals.length; col++) {
                    hiddenArray[row][col] = Double.valueOf(vals[col]);
                }
                row++;
            }    
        }
        catch(FileNotFoundException e) {
            System.out.println("file not found - "+e.getMessage());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 2015-08-19
      • 2020-10-04
      • 2019-01-23
      相关资源
      最近更新 更多